如何在CommonJS中使用ES6模块



我见过在CommonJS Node应用程序中导入ES6模块?如何使用带有commonjs的ES6模块和https://nodejs.org/api/esm.html#esm_enabling

但我还是不明白。javascript还是个新手。

根本问题是";我需要做什么?使我能够在CommonJS中使用ES6模块的位在哪里?

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

index.jsCommonJS

const crypto = require('crypto');  // to show this is a commonJS module
import('./path/to/mod.mjs').then(mod =>
console.log(mod.msg);    //  "Hello world!"
);

mod.mjsES模块

export const msg = "Hello world!";

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

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

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

utils.js

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

index.js

require('./utils.js').then(([{ default: pad }, { default: toUpper }]) => {
console.log(pad(toUpper('hello world'), 17, '*'));
}); 

ESModules和CommonJS是互斥的,所以不能"使用CommonJS内部的ES6模块";。

然而,在某种程度上,你可以";使用ESModules内部的CommonJS";,如果通过";CommonJS";你只是指CCD_ 7函数。您可以使用module.createRequire():创建require()函数的实例

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');

NodeJS的文档中有一章介绍了两个模块系统之间的互操作性。这很有帮助,你可能想看看。

最新更新