我想在我的文件中使用 import,但我找不到正确替换我的 require 的方法
查看我要替换的代码
const object = {
first: require('../example/first.json').EXL.PUBLIC,
second: require('../example/second.json').EXL.PUBLIC,
third: require('../example/third.json').EXL.PUBLIC
}
第一个问题是如何将这些东西直接导入到对象中?就像我对 require 所做的那样?
第二个,如何使用 .EXL.PUBLIC
命令导入?直接导入json文件的右侧分支?
最佳答案
First question is how can I import those stuff directly to an object?
你不能,你必须导入它们,然后将它们添加到对象中。
The second one, how can I use import with the '.EXL.PUBLIC' command?
您必须导入该项目,然后提取该属性。
我假设您使用的是 Node.js:
v8 到 v11
在 .mjs
模块中,您可以这样做:
import firstRoot from "../example/first.json";
import secondRoot from "../example/second.json";
import thirdRoot from "../example/third.json";
const object = {
first: firstRoot.EXL.PUBLIC,
second: secondRoot.EXL.PUBLIC,
third: thirdRoot.EXL.PUBLIC
};
v12
您仍然可以像 v11 中那样进行操作。
如果您通过 package.json
中的新 "type": "module"
将 ESM 与 .js
文件结合使用,则需要添加 --experimental-json-modules
标志以启用 JSON 加载。有关 v12 支持的更多信息 here ,但请注意,尚不支持 --type
(如果支持,可能会是 --entry-type
),并且 JSON 标志为 --experimental-json-modules
,而不是--experimental-json-loader
)。
关于javascript - 如何使用es6 import代替require?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55609201/