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);
}

示例中的这段复制粘贴代码(有效)在我的项目中有错误:

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

如果我调试它,我可以看到 suburbs 是一个 objectc,而不是一个数组,所以没有定义过滤函数。

然而在示例中被注释的建议是一个数组。如果我这样重写建议,一切正常:

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

所以...什么 json! prefix在import中是干什么的?

为什么我不能把它放在我的代码中?一些 babel 配置?

首先你需要安装json-loader:

npm i json-loader --save-dev

那么,有两种使用方法:

  1. 为了避免在每个 import 中添加 json-loader 你可以在 webpack.config 中添加这一行:

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

    然后像这样导入 json 个文件

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

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

注:webpack 2.* 而不是关键字 loaders 需要使用 rules.,

webpack 2.*默认使用json-loader

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

当我无法用 ES6 TypeScript 2.6 加载 json-file 时发现了这个线程。我不断收到此错误:

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

为了让它工作,我必须先声明模块。我希望这会为某人节省几个小时。

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

...

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

如果我试图从 json-loader 中省略 loader,我会从 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

这只适用于 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 };
});

安装 json-loader 后,现在您可以简单地使用:

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

或者,更简单地说:

import suburbs from '../suburbs';

节点 v8.5.0+

您不需要 JSON 加载器。 Node为ECMAScript Modules (ES6 Module support)提供了--experimental-modules标志,你可以这样使用

node --experimental-modules myfile.mjs

那就很简单了

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

然后将其绑定到变量 myJSON