如何在 ecmascript 6 中导入 json 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34944099/
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
How to import a json file in ecmascript 6?
提问by Nikita Jajodia
How can I access a json file in Ecmascript 6 ? The following doesn't work:
如何在 Ecmascript 6 中访问 json 文件?以下不起作用:
import config from '../config.json'
import config from '../config.json'
This works fine if I try to import a JavaScript file.
如果我尝试导入 JavaScript 文件,这可以正常工作。
采纳答案by Gilbert
A simple workaround:
一个简单的解决方法:
config.js
配置文件
export default
{
// my json here...
}
then...
然后...
import config from '../config.js'
does not allow import of existing .json files, but does a job.
不允许导入现有的 .json 文件,但可以完成工作。
回答by williamli
In TypeScript or using Babel, you can import jsonfile in your code.
在 TypeScript 或使用 Babel 中,您可以在代码中导入json文件。
// Babel
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
Reference: https://hackernoon.com/import-json-into-typescript-8d465beded79
参考:https: //hackernoon.com/import-json-into-typescript-8d465beded79
回答by Simone
Unfortunately ES6/ES2015 doesn't support loading JSON via the module import syntax. But...
不幸的是,ES6/ES2015 不支持通过模块导入语法加载 JSON。但是……
There are many ways you can do it. Depending on your needs you can either look into how to read files in JavaScript (window.FileReadercould be an option if you're running in the browser) or use some other loaders as described in other questions(assuming you are using NodeJS).
有很多方法可以做到。根据您的需要,您可以研究如何在 JavaScript 中读取文件(window.FileReader如果您在浏览器中运行,这可能是一个选项)或使用其他问题中描述的其他一些加载器(假设您使用的是 NodeJS)。
IMO simplest way is probably to just put the JSON as a JS object into an ES6 module and export it. That way you can just import it where you need it.
IMO 最简单的方法可能是将 JSON 作为 JS 对象放入 ES6 模块并导出。这样你就可以将它导入到你需要的地方。
Also worth noting if you're using Webpack, importing of JSON files will work by default(since webpack >= v2.0.0).
另外值得注意的是,如果您使用的是 Webpack,默认情况下可以导入 JSON 文件(因为webpack >= v2.0.0)。
import config from '../config.json';
回答by Francisco Neto
I'm using babel+browserify and I have a JSON file in a directory ./i18n/locale-en.json with translations namespace (to be used with ngTranslate).
我正在使用 babel+browserify 并且我在目录 ./i18n/locale-en.json 中有一个带有翻译命名空间的 JSON 文件(与 ngTranslate 一起使用)。
Without having to export anything from the JSON file (which btw is not possible), I could make a default import of its content with this syntax:
无需从 JSON 文件中导出任何内容(顺便说一句,这是不可能的),我可以使用以下语法对其内容进行默认导入:
import translationsJSON from './i18n/locale-en';
回答by Anonymous User 2903
If you're using node you can:
如果您使用节点,您可以:
const fs = require('fs');
const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time
OR
或者
const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');
Else:
别的:
// config.js
{
// json object here
}
// script.js
import { config } from '../config.js';
OR
或者
import * from '../config.json'
回答by Pat Migliaccio
Depending on your build tooling and the data structure within the JSON file, it may require importing the default.
根据您的构建工具和 JSON 文件中的数据结构,它可能需要导入default.
import { default as config } from '../config.json';
e.g. usage within Next.js
例如使用范围内 Next.js
回答by trusktr
In a browser with fetch (basically all of them now):
在带有 fetch 的浏览器中(现在基本上都是):
At the moment, we can't importfiles with a JSON mime type, only files with a JavaScript mime type. It might be a feature added in the future (official discussion).
目前,我们不能import使用 JSON mime 类型的文件,只能使用 JavaScript mime 类型的文件。它可能是将来添加的功能(官方讨论)。
fetch('./file.json')
.then(response => response.json())
.then(obj => console.log(obj))
In Node.js v13.2+:
在 Node.js v13.2+ 中:
It currently requires the --experimental-json-modulesflag, otherwise it isn't supported by default.
它目前需要--experimental-json-modulesflag,否则默认情况下不支持。
Try running
尝试跑步
node --input-type module --experimental-json-modules --eval "import obj from './file.json'; console.log(obj)"
and see the obj content outputted to console.
并查看输出到控制台的 obj 内容。
回答by Avram Tudor
A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.
有点晚了,但我在尝试为我的 Web 应用程序提供分析时偶然发现了同样的问题,其中涉及基于 package.json 版本发送应用程序版本。
Configuration is as follows: React + Redux, Webpack 3.5.6
配置如下:React + Redux、Webpack 3.5.6
The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.
自 Webpack 2+ 以来,json-loader 并没有做太多事情,因此在对它进行了一些摆弄之后,我最终将其删除。
The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.
实际上对我有用的解决方案只是使用 fetch。虽然这很可能会强制执行一些代码更改以适应异步方法,但它工作得很好,特别是考虑到 fetch 将提供动态 json 解码。
So here it is:
所以这里是:
fetch('../../package.json')
.then(resp => resp.json())
.then((packageJson) => {
console.log(packageJson.version);
});
Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.
请记住,由于我们在这里专门讨论 package.json,因此该文件通常不会捆绑在您的生产版本(甚至开发人员)中,因此您必须使用 CopyWebpackPlugin 才能访问它在使用 fetch 时。

