在 React 组件中导入 Json 文件 [英] import a Json file in a React Component

查看:39
本文介绍了在 React 组件中导入 Json 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 React 组件中加载languages.json 文件.当我想导入 json 文件时,我在第一步收到以下错误.这是错误:

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 (........)

我正在使用 webpack,这是配置文件:

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"

这是我导入文件的方式(ES6 格式):

This is how I'm tring to import the file (ES6 format):

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

另外,我检查了json文件格式并验证了它!那么,您认为问题出在哪里?

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

推荐答案

azium 正确的是需要一个加载器,但这是一个很好的配置:

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

npm 命令

> npm install json-loader --save-dev

webpack.config.js

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

通过将 json 扩展添加到 resolve,您无需在 import 语句中指定它.

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

这篇关于在 React 组件中导入 Json 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆