user2670996 user2670996 - 6 months ago 23
Javascript Question

es6 modules implementation, how to load a json file

I'm implementing an example from

Important code is like this:

import React, { Component } from 'react';
import suburbs from 'json!../suburbs.json';

function getSuggestions(input, callback) {
const suggestions = suburbs
.filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))
.sort((suburbObj1, suburbObj2) =>
suburbObj1.suburb.toLowerCase().indexOf(lowercasedInput) -
.slice(0, 7)
.map(suburbObj => suburbObj.suburb);

// 'suggestions' will be an array of strings, e.g.:
// ['Mentone', 'Mill Park', 'Mordialloc']

setTimeout(() => callback(null, suggestions), 300);

This copy-paste code from the example (that works), has an error in my project:

Error: Cannot resolve module 'json' in /home/juanda/redux-pruebas/components

If I take out the preffix json!:

import suburbs from '../suburbs.json';

This way I got not errors at compile time (import is done).
However I got errors when I execute it:

Uncaught TypeError: _jsonfilesSuburbsJson2.default.filter is not a function

If I debug it I can see suburbs is an objectc, not an array so filter function is not defined.

However in the example is commented suggestions is an array. If I rewrite suggestions like this, everything works:

const suggestions = suburbs
var suggestions = [ {
'suburb': 'Abbeyard',
'postcode': '3737'
}, {
'suburb': 'Abbotsford',
'postcode': '3067'
}, {
'suburb': 'Aberfeldie',
'postcode': '3040'
} ].filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))

So... what json! preffix is doing in the import?

Why can't I put it in my code? Some babel configuration?


You need to install json-loader and then add this line to webpack.config (, and webpack.standalone.config.js)

loaders: [
   { test: /\.json$/, loader: 'json' },
   // other loaders 

you can then import json files like this

import suburbs from '../suburbs.json';

without having to adding json-loader in each import.

If you don't want to change the config files, just use json-loader as in your example :

import suburbs from 'json!../suburbs.json';