无法在React.js中读取json,意外令牌错误

时间:2017-05-18 15:25:16

标签: json reactjs

我无法从React.js中的json文件中获取数据 我在JSLINT上检查了myJSON并使用了Windows系统。

我没有尝试显示它只是存储在一个变量中,它仍然是一个错误:

./src/app/document.json中的错误

模块构建失败:SyntaxError:C:/Users/Ant/Documents/reactapplication/src/app/document.json:意外的令牌,预期; (2:14)

1 | {
2 |         "name":"Product",
  |               ^
3 |         "properties":
4 |         {
5 |                 "id":

这是我的index.js

var React = require('react');
var ReactDOM = require('react-dom');

var App = require('./App');
var Json = require('./document');

ReactDOM.render(<div>Hello 123</div>, document.getElementById('app'));

我试图将json存储为Json中的对象,但我无法做到。

我的webpack.config

var path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
entry: SRC_DIR + "/app/index.js",
output: {
    path: DIST_DIR + "/app",
    filename: "bundle.js",
    publicPath: "/app/"
},
module: {
    loaders: [
        {
            test: /\.js?/,
            include: SRC_DIR,
            loader: "babel-loader",
            query: {
                presets: ["react", "es2015", "stage-2"]
            }
        }
    ]
}
};

module.exports = config; 

依赖关系是:

"dependencies": {
"fixed-data-table": "^0.6.4",
"react": "^15.5.4",
"react-dom": "^15.5.4"
  },
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"json-loader": "^0.5.4",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
}

3 个答案:

答案 0 :(得分:1)

<强> ES6 / ES2015

您可以使用import as语法加载JSON:

// import the JSON
import * as data from './document.json';
// use the JSON data
console.log(data);

<强>需要

如果您打算使用require导入JSON,请确保将JSON的值分配给module.exports,这样:

// document.js
module.exports = { "id": 1, "name":"foo" };

.json更改为.js文件类型。

这应该允许声明var Json = require('./document');起作用。

希望这有帮助!

答案 1 :(得分:1)

找到解决方案:

将以下代码添加到webpack中的加载器:

{ test: /\.json$/, loader: 'json-loader' }

Webpack 2.0默认使用json-loader而不必显式调用它,这一行确保json-loader将文件呈现为json。

您可以继续使用require()import来加载json。

答案 2 :(得分:0)

也许尝试将resolve.extensions添加到您的webpack配置

{
    // ...
    resolve: {
        extensions: ['json', 'js', 'jsx'],
    },
    // ...
}
相关问题