如何在CommonJS中使用ES6模块?

问题描述 投票:0回答:3

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

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

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

javascript es6-modules
3个回答
33
投票

在 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, '*'));
}); 

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');

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


0
投票

我试图使用 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();
            });
        });
    });
})();
© www.soinside.com 2019 - 2024. All rights reserved.