如何使用 es6 import 而不是 require?

How to use es6 import instead of 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).