ES6模块如何加载json文件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (78)

我正在实现一个例子https://github.com/moroshko/rep

重要代码如下:

import React, { Component } from 'react';
import suburbs from 'json!../suburbs.json';

function getSuggestions(input, callback) {
  const suggestions = suburbs
    .filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))
    .sort((suburbObj1, suburbObj2) =>
      suburbObj1.suburb.toLowerCase().indexOf(lowercasedInput) -
      suburbObj2.suburb.toLowerCase().indexOf(lowercasedInput)
    )
    .slice(0, 7)
    .map(suburbObj => suburbObj.suburb);

  // 'suggestions' will be an array of strings, e.g.:
  //   ['Mentone', 'Mill Park', 'Mordialloc']

  setTimeout(() => callback(null, suggestions), 300);
}

此示例中的复制粘贴代码(有效)在我的项目中有一个错误:

Error: Cannot resolve module 'json' in /home/juanda/redux-pruebas/components

可以:

import suburbs from '../suburbs.json';

这样我就不会在编译时出错(导入就完成了)。但是,当我执行它时会出现错误:

Uncaught TypeError: _jsonfilesSuburbsJson2.default.filter is not a function

如果我调试它,我可以看到郊区是一个objectc,而不是一个数组,因此没有定义Filter函数。

然而,在这个例子中,注释建议是一个数组。如果我重写这样的建议,一切都会成功:

  const suggestions = suburbs
  var suggestions = [ {
    'suburb': 'Abbeyard',
    'postcode': '3737'
  }, {
    'suburb': 'Abbotsford',
    'postcode': '3067'
  }, {
    'suburb': 'Aberfeldie',
    'postcode': '3040'
  } ].filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))

为什么我不能把它写在我的代码里?一些Babel的配置?

提问于
用户回答回答于

首先,您需要安装json-loader:

npm i json-loader --save-dev

然后,有两种方法可以使用它:

  1. 为了避免添加json-loader在每一个import你可以添加到webpack.config这一行: 装载机:{测试:/。JSON$/,加载程序:‘json’},//其他加载程序然后进口json像这样的文件 从‘./郊区’进口郊区;
  2. 使用json-loader直接在你的import,如您的示例所示: 从‘json!/郊区’进口郊区;

注:webpack 2.*而不是关键字loaders需要使用rules...

webpack 2.*使用json-loader默认情况下

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change. v2.1.0-beta.28

用户回答回答于

如果json文件是数组,json加载器不会加载它,在本例中,您需要确保它有一个键,例如

{
    "items": [
    {
      "url": "https://api.github.com/repos/vmg/redcarpet/issues/598",
      "repository_url": "https://api.github.com/repos/vmg/redcarpet",
      "labels_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/labels{/name}",
      "comments_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/comments",
      "events_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/events",
      "html_url": "https://github.com/vmg/redcarpet/issues/598",
      "id": 199425790,
      "number": 598,
      "title": "Just a heads up (LINE SEPARATOR character issue)",
    },
    ..... other items in array .....
]}

扫码关注云+社区