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

我正在实现来自 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! 前缀在进口里?

为什么我不能把它放在我的代码? 一些巴贝尔配置?

135039 次浏览

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. Use json-loader directly in your import, as in your example:

    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-loader doesn't load json file if it's array, in this case you need to make sure it has a key, for example

{
"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 .....
]}

Found this thread when I couldn't load a json-file with ES6 TypeScript 2.6. I kept getting this error:

TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

To get it working I had to declare the module first. I hope this will save a few hours for someone.

declare module "json-loader!*" {
let json: any;
export default json;
}


...


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

If I tried to omit loader from json-loader I got the following error from webpack:

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

This just works on React & React Native

const data = require('./data/photos.json');


console.log('[-- typeof data --]', typeof data); // object




const fotos = data.xs.map(item => {
return { uri: item };
});

With json-loader installed, now you can simply use:

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

or, even more simply:

import suburbs from '../suburbs';

Node v8.5.0+

You don't need JSON loader. Node provides ECMAScript Modules (ES6 Module support) with the --experimental-modules flag, you can use it like this

node --experimental-modules myfile.mjs

Then it's very simple

import myJSON from './myJsonFile.json';
console.log(myJSON);

Then you'll have it bound to the variable myJSON.