我试图在React组件中加载languages.json文件。我想在导入json文件的第一步时收到以下错误。这是错误:
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,这是配置文件:
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')
}
]
}
};
我安装了这些软件包:
"babel-core": "^6.2.1",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.1.18"
这就是我导入文件的方式(ES6格式):
import lang_code from '../../app/languages.json';
另外,我检查了json文件格式并验证了它!那么,您认为问题在哪里?
答案 0 :(得分:8)
azium是正确的,需要一个加载器,但这里是良好衡量的配置:
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
声明中指定。