es6模块实现,如何加载json文件 [英] es6 modules implementation, how to load a json file
问题描述
我正在实施 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
如果我取出前缀json!:
If I take out the preffix 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
如果我调试它,我可以看到郊区是一个objectc,而不是一个数组,所以没有定义过滤器功能。
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))
所以......什么是json! preffix正在进行导入?
So... what json! preffix is doing in the import?
为什么我不能把它放在我的代码中?一些babel配置?
Why can't I put it in my code? Some babel configuration?
推荐答案
首先你需要安装 json-loader
:
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:
-
为了避免添加 import 中的/ webpack / json-loaderrel =nofollow noreferrer>
json-loader
你可以添加到webpack.config
这一行:
In order to avoid adding
json-loader
in eachimport
you can add towebpack.config
this line:
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
// other loaders
]
然后导入 json
这样的文件
import suburbs from '../suburbs.json';
使用 json-loader
直接在 import
中,就像在你的例如:
Use json-loader
directly in your import
, as in your example:
import suburbs from 'json!../suburbs.json';
注意:
在 webpack 2。*
而不是关键字 loaders
需要使用< a href =https://webpack.js.org/how-to/upgrade-from-webpack-1/#module-loaders-is-now-module-rules =nofollow noreferrer> 规则
。
还 webpack 2 。*
默认使用 json-loader
*。现在支持json文件而不使用json-loader。你仍然可以使用它。这不是一个重大改变。
*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.
这篇关于es6模块实现,如何加载json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!