ES6 modules implementation, how to load a json file
First of all you need to install json-loader
:
npm i json-loader --save-dev
Then, there are two ways how you can use it:
-
In order to avoid adding
json-loader
in eachimport
you can add towebpack.config
this line:loaders: [ { test: /\.json$/, loader: 'json-loader' }, // other loaders ]
Then import
json
files like thisimport suburbs from '../suburbs.json';
-
Use
json-loader
directly in yourimport
, as in your example:import suburbs from 'json!../suburbs.json';
Note:
In webpack 2.*
instead of keyword loaders
need to use rules
.,
also webpack 2.*
uses json-loader
by default
*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.
v2.1.0-beta.28
json-loader doesn't load json file if it's array, in this case you need to make sure it has a key, for example
{
"items": [
{
"url": "https://api.github.com/repos/vmg/redcarpet/issues/598",
"repository_url": "https://api.github.com/repos/vmg/redcarpet",
"labels_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/labels{/name}",
"comments_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/comments",
"events_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/events",
"html_url": "https://github.com/vmg/redcarpet/issues/598",
"id": 199425790,
"number": 598,
"title": "Just a heads up (LINE SEPARATOR character issue)",
},
..... other items in array .....
]}
This just works on React & React Native
const data = require('./data/photos.json');
console.log('[-- typeof data --]', typeof data); // object
const fotos = data.xs.map(item => {
return { uri: item };
});