在同一个 NodeJS 项目中使用 Import 和 Require

Mar*_*ado 9 javascript commonjs node.js requirejs es6-modules

我有一个 Node.js 项目,其模块是使用 Common.JS 方式导入的require。但是,需要导入仅 ESM 的包。

在我的项目中使用 ESM 的一种方法import from是添加"type": "module"到我的package.json文件中。然而,所有的requires工作都停止了。

我验证了一种解决方案是从包中创建 require 模块module

import { createRequire } from "module";
const require = createRequire(import.meta.url);
Run Code Online (Sandbox Code Playgroud)

然而,整个(大型)项目都有导入require,在我看来,必须将这个解决方案添加到每个项目中是不可行的。

所以我想知道是否有一种优雅的方法来声明require一次并在整个项目中使用它。

或者,还有比创建 ESMrequire或替换 ESM 的所有内容更优雅的解决方案吗?

mor*_*ney 0

要一起使用requireimport,您需要使用动态import()表达式将 ES 模块加载到 CommonJS 上下文中。

提供解决方案的常见 Node.js 错误消息如下所示:

Error [ERR_REQUIRE_ESM]: require() of ES Module <path> from <path> not supported.
Instead change the require of <path> in <path> to a dynamic import() which is available in all CommonJS modules.
Run Code Online (Sandbox Code Playgroud)

lodash这是使用and的示例lodash-es

Error [ERR_REQUIRE_ESM]: require() of ES Module <path> from <path> not supported.
Instead change the require of <path> in <path> to a dynamic import() which is available in all CommonJS modules.
Run Code Online (Sandbox Code Playgroud)