【问题标题】:Cannot read json in React.js, unexpected token error无法在 React.js 中读取 json,出现意外的令牌错误
【发布时间】: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 语句,都抛出相同的错误。

标签: json reactjs


【解决方案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'); 工作。

希望对您有所帮助!

【讨论】:

  • 我不想修改我的json文件并按原样使用,除了require()还有其他导入json数据的方法
  • 您可能需要额外的 Webpack 加载器,请参阅 stackoverflow.com/questions/33650399/…
【解决方案2】:

找到解决方案:

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

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

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

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

【讨论】:

    【解决方案3】:

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

    {
        // ...
        resolve: {
            extensions: ['json', 'js', 'jsx'],
        },
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多