如何在 CommonJS 中使用 ES6 模块?

Dav*_*ton 23 javascript es6-modules

我见过 在 CommonJS Node 应用程序中导入 ES6 模块? 如何将 ES6 模块与 commonjshttps://nodejs.org/api/esm.html#esm_enabling一起使用

我还是不明白。对 javascript 相当陌生。

基本问题是“我需要做什么以及这些位在哪里才能使我能够在 CommonJS 中使用 ES6 模块?

Mik*_*keM 29

在 Node.js 中,如果要在 CommonJS 模块中导入 ES 模块,可以在 ES 模块上使用动态import.mjs文件扩展名。例如:

index.js CommonJS

const crypto = require('crypto');  // to show this is a commonJS module

import('./path/to/mod.mjs').then(mod =>
  console.log(mod.msg);    //  "Hello world!"
);
Run Code Online (Sandbox Code Playgroud)

mod.mjs ES 模块

export const msg = "Hello world!";
Run Code Online (Sandbox Code Playgroud)

两个示例说明如何import在 CommonJS 模块中使用来导入全部或部分包lodash-es

export const msg = "Hello world!";
Run Code Online (Sandbox Code Playgroud)
import('lodash-es').then(_ => {
  console.log(_.pad(_.toUpper('hello world'), 17, '*'));
});
Run Code Online (Sandbox Code Playgroud)

或者您可以将您需要的内容导入到不同的 CommonJS 模块中,然后导出Promise您可以importrequire.

实用程序.js

Promise.all([
  import('lodash-es/pad.js'),
  import('lodash-es/toUpper.js'),
])
.then(([{ default: pad }, { default: toUpper }]) => {
  console.log(pad(toUpper('hello world'), 17, '#'));
});
Run Code Online (Sandbox Code Playgroud)

索引.js

module.exports = Promise.all([
  import('lodash-es/pad.js'),
  import('lodash-es/toUpper.js'),
]);
Run Code Online (Sandbox Code Playgroud)


Dmi*_*sky 7

ESModules 和 CommonJS 是互斥的,所以你不能“在 CommonJS 中使用 ES6 模块”。

然而,在某种程度上,你可以“在 ESModules 中使用 CommonJS”,如果“CommonJS”仅指的是函数require()require()您可以使用以下命令创建函数实例module.createRequire()

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');
Run Code Online (Sandbox Code Playgroud)

NodeJS 的文档中有一个章节介绍了两个模块系统之间的互操作性。这非常有帮助,您可能想检查一下。

  • 这不再是真的。通过在 Node 中实现动态导入,您现在可以通过使用 `import()` **函数**(返回模块的 Promise)在 Commonjs 中使用 ES 模块,并且 `import` 语法现在也支持导入 Commonjs 模块 (8认同)