javascript - 如何使用es6 import代替require?

标签 javascript ecmascript-6 import export require

我想在我的文件中使用 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/

相关文章:

javascript - 无法获取数据并且 React 没有给出任何错误消息

python - 如何导入一个模块的所有功能?

javascript - 如何使用原型(prototype)继承编写整洁灵活的复杂 javascript 应用程序

javascript - 在加载到服务器期间将 .mp3 文件转换为 юogg 的最佳方法是什么?

javascript - get 中显示的 Backbone 上一个属性

mysql - 将多个mssql数据库与php合并为一个mysql

python - python3中的导入更改

javascript - 如何从 Vue.js 中的数组中删除项目

javascript - 将整个代码块包装在 Promise 中时 Promise 和 Deferred 之间的区别?

javascript - 如何在 React + Typescript 中将状态更新到之前的状态