Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

reactjs - import a Json file in a React Component

I'm trying to load languages.json file in a React component. I'm getting the following error at the very first step when I want to import the 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'm using webpack and here is the config 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'm tring to import the file (ES6 format):

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

azium is correct that a loader is needed, but here's the configuration for good measure:

npm command

> npm install json-loader --save-dev

webpack.config.js

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

By adding the json extension to resolve, you won't need to specify it in your import statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...