【发布时间】:2017-10-18 12:18:03
【问题描述】:
我无法从 React.js 中的 json 文件中获取数据 我在 JSLINT 上检查了 myJSON 并使用了 Windows 系统。
我没有尝试显示它,只是存储在一个变量中,它仍然抛出一个错误:
./src/app/document.json 中的错误
模块构建失败:SyntaxError: C:/Users/Ant/Documents/reactapplication/src/app/document.json: Unexpected token, expected ; (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"
}
【问题讨论】:
-
也许在需要时尝试添加 json 扩展。
require('./document.json');webpack 默认应该能够在没有任何额外加载器的情况下导入 json。 -
另外,由于您使用的是 webpack,您应该使用 es6 导入语法而不是 require。
-
我尝试添加 .json 以及使用 import 语句,都抛出相同的错误。