我正在从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!导入中的前缀是做什么的?
为什么我不能把它放在我的代码中?一些 babel 配置?