I'm implementing an example from 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);
}

This copy-paste code from the example (that works), has an error in my project:

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

如果我go 掉前缀json!:

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

This way I got not errors at compile time (import is done). However I got errors when I execute it:

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

If I debug it I can see suburbs is an objectc, not an array so filter function is not defined.

However in the example is commented suggestions is an array. If I rewrite suggestions like this, everything works:

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

所以...什么杰森!前缀在导入做什么?

为什么我不能把它写进我的代码里?一些巴别塔配置?

推荐答案

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. import中直接使用json-loader,如示例所示:

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

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.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相关问答推荐

如何使用Laravel在MariaDB JSON kolumn中使用unicode字符

SWIFT中的网络经理

将JSON输入子数组转换为字符串顺序列表输出

如何在Gatsby/Reaction中获取JSON-File子 node

如何在PowerShell中访问嵌套的JSON字段

解析SQL中的嵌套JSON

无法访问id的第三级json

展平多个数组以保持顺序

如何使用jolt规范将一个对象添加到另一个对象中并删除该对象

添加到数组时出错:找不到Add的重载和参数计数:1

判断golang中解析的json响应中是否存在所需的json键(不是值)

在循环中将变量添加到 bash 数组

IE8 原生 JSON.parse 错误导致堆栈溢出

什么是类型和类型令牌?

Rails 中奇怪的 JSON Javascript 问题

如何在不消除对象歧义的情况下使用 circe 解码 ADT

在视图中将 .Net 对象转换为 JSON 对象

ASP.NET MVC 读取原始 JSON 发布数据

如何访问 JSON 对象数组的第一个元素?

如何在 Java 中将 YAML 转换为 JSON?