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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33650399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:18:49  来源:igfitidea点击:

ES6 modules implementation, how to load a json file

javascriptjsonreactjswebpack

提问by user2670996

I'm implementing an example from https://github.com/moroshko/react-autosuggest

我正在从https://github.com/moroshko/react-autosuggest实现一个例子

Important code is like this:

重要的代码是这样的:

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

If I take out the prefix json!:

如果我去掉前缀 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

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

So... what json! prefix is doing in the import?

所以......什么json!导入中的前缀是做什么的?

Why can't I put it in my code? Some babel configuration?

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

回答by Alexander T.

First of all you need to install json-loader:

首先你需要安装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-loaderin each importyou can add to webpack.configthis line:

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

    Then import jsonfiles like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loaderdirectly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    
  1. 为了避免添加json-loader每个import你可以添加到webpack.config这一行:

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

    然后json像这样导入文件

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

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

Note:In webpack 2.*instead of keyword loadersneed to use rules.,

注意:webpack 2.*代替关键字时loaders需要使用rules.,

also webpack 2.*uses json-loaderby default

也默认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 文件现在支持没有 json-loader。你仍然可以使用它。这不是一个突破性的变化。

v2.1.0-beta.28

回答by DmitrySemenov

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

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

回答by Kiko Seijo

This just works on React & React Native

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

回答by Let Me Tink About It

With json-loaderinstalled, now you can simply use:

随着json-loader安装的,现在你可以简单地使用:

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

or, even more simply:

或者,更简单地说:

import suburbs from '../suburbs';

回答by Evan Carroll

Node v8.5.0+

节点 v8.5.0+

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

您不需要 JSON 加载程序。Node 提供了带有标志的ECMAScript Modules(ES6 模块支持)--experimental-modules,你可以像这样使用它

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.

然后你会将它绑定到变量myJSON

回答by Ogglas

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

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

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

TS2307 (TS) 找不到模块 '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 loaderfrom json-loaderI got the following error from webpack:

如果我试图省略loaderfromjson-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

突破性变化:在使用加载器时不再允许省略“-loader”后缀。您需要指定 'json-loader' 而不是 'json',参见https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed