我见过 在 CommonJS Node 应用程序中导入 ES6 模块? 如何将 ES6 模块与 commonjs 一起使用 和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.mjs ES 模块
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
,然后您可以 import
或 require
。
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”仅指
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');
NodeJS 文档中有一个章节介绍了两个模块系统之间的互操作性。很有帮助,你可能想看看。
我试图使用 mocha 和 chai 编写测试代码。但我遇到了错误。因为我的项目位于 common js 模块中,而 chai 在底层使用的是 ex6 模块。然后我能够使用代码中的动态导入解决问题。
(async () => {
const chai = await import('chai'); // import the chai using the dynamic import
const { expect } = chai;
const Item = require('../../crudModels');
describe('Item model', function () {
it('should be invalid if title is empty', function (done) {
var i = new Item();
i.validate(function (err) {
expect(err.errors.title).to.exist;
done();
});
});
});
})();