ES6模块实现,如何加载json文件

JavaScript

乐米亚

2020-03-12

我正在从https://github.com/moroshko/react-autosuggest实现一个示例

重要代码如下:

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

如果我删除前缀json !:

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

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

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

如果我调试它,我可以看到郊区是一个对象,而不是一个数组,因此未定义过滤器功能。

但是,在示例中,注释的建议是一个数组。如果我像这样重写建议,那么一切都会起作用:

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

所以...什么json!前缀是在导入吗?

为什么不能将其放入代码中?一些通天塔配置?

第1345篇《ES6模块实现,如何加载json文件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
飞云神乐 2020.03.13

json-loader如果是数组,则不会加载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 .....
]}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android