如何在 ECMAScript 6 中导入 JSON 文件? [英] How to import a JSON file in ECMAScript 6?

查看:39
本文介绍了如何在 ECMAScript 6 中导入 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 ECMAScript 6 中访问 JSON 文件?

How can I access a JSON file in ECMAScript 6?

以下不起作用:

import config from '../config.json'

如果我尝试导入 JavaScript 文件,这可以正常工作.

This works fine if I try to import a JavaScript file.

推荐答案

使用 ES 模块导入 JSON 已在 2020 年中期作为功能提交给 TC39,并且(在此编辑时)处于第 3 阶段,这是最后一个在被规范接受之前的阶段(参见 https://github.com/tc39/proposal-json-modules 了解更多详情).登陆后,您将可以将其用作:

Importing JSON using ES modules was submitted as feature to TC39 in mid 2020, and is (at the time of this edit) in stage 3, which is the last stage before being accepted in to the spec (see https://github.com/tc39/proposal-json-modules for more details). Once landed, you will be able to use it as:

import someName from "./some/path/to/your/file.json";

其中 someName 实际上是 JSON 数据描述的 JS 对象的变量名称.(当然,请注意这是从 JSON 源导入 JavaScript,它不会导入 JSON").

Where someName is effectively the name of the variable for the JS object described by the JSON data. (And of course, note that this imports JavaScript from a JSON source, it does not "import JSON").

如果您使用的是足够现代的打包器(例如 esbuild 或类似工具),或者您使用的是足够新的转译器(例如 babel),那么您已经可以使用此语法而不必担心支持.

If you're using a modern enough bundler (like esbuild or the like) or you're using a recent enough transpiler (like babel) then you can already use this syntax without having to worry about support.

或者,如果您拥有 JSON 文件的所有权,您也可以使用最少的额外代码将您的 JSON 转换为有效的 JS 文件:

Alternatively, if you have the luxury of ownership of JSON files you can also turn your JSON into valid JS files with a minimum of extra code:

config.js

export default
{
  // my json here...
}

然后...

import config from '../config.js'

不允许导入现有的 .json 文件,但可以执行.

does not allow import of existing .json files, but does a job.

这篇关于如何在 ECMAScript 6 中导入 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆