Import Json file into React component

I am trying to load a languages.json file into a React component. I get the following error in the first step when I want to import a json file. Here is the error:

ERROR in ./app/languages.json
Module parse failed: /.../languages.json Unexpected token (1:12)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:12)
    at Parser.pp.raise (........)

I am using webpack and here is the configuration file:

   var path = require('path');
   var webpack = require('webpack');

   module.exports = {
       entry: ['./app/main.jsx'],
       devtool: 'cheap-module-eval-source-map',
       output: { path: __dirname+"/app", filename: 'bundle.js' },
       module: {
           loaders: [
              {   test: /\.jsx?$/,
                  loader: 'babel-loader',
                  query: { presets: ['es2015', 'react'] },
                  include: path.join(__dirname, 'src')
              }
          ]
      }
  };

and I have these packages installed:

"babel-core": "^6.2.1",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.1.18"

This is how I try to import a file (ES6 format):

import lang_code from '../../app/languages.json';

Also, I checked the json file format and checked it! So what do you think is the problem?

+4
source share
1 answer

azium is correct that you need a bootloader, but here is the configuration for a good measure:

npm team

> npm install json-loader --save-dev

webpack.config.js

 module.exports = {
    ....
    resolve: {
        extensions: ['', '.js', '.jsx', '.json']
    },
    ...
   module: {
       ...
            {
                test: /\.json$/,
                loader: 'json'
            }
       ...
   }
}

json resolve, import.

+8

All Articles