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

ES6 modules implementation, how to load a json file

本文关键字:加载 json 文件 何加载 模块 实现 ES6      更新时间:2023-09-26

我正在实现一个来自 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!前缀在导入中做什么?

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

首先你需要安装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 加载器的 *.json 文件。您仍然可以使用它。这不是重大更改。

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

仅适用于 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 模块(ES6 模块支持(提供了带有 --experimental-modules 标志,你可以这样使用它

node --experimental-modules myfile.mjs

然后很简单

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

然后,您将它绑定到变量myJSON

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

TS2307 (TS( 找不到模块"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收到以下错误:

中断性变更:不再允许省略"-loader"后缀 使用加载程序时。 您需要指定"json-loader"而不是"json", 见 https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed