0

我查看了许多关于 SO 的类似问题,但没有找到明确的答案。

我正在编写一个 npm CLI 工具,它应该动态导入指定的模块并对该模块的导出运行一些操作。

在我的 npm 包中,我已经指定"type": "module"并且我的二进制文件是bin/generator.mjs.

我尝试使用它的方式是:❯ ./bin/generator.mjs path/to/test-module.js [other args]- 然后在生成器中我这样做:

const modulePath = "file://" + path.resolve(inputFilename);
const objs = await import(modulePath);

使用此配置,我可以在命令行上指定一个 ES6 模块,并且生成器工作正常,但是,如果我指定一个 CommonJS 模块,我会得到:

const Library = require('some-library');
                ^
ReferenceError: require is not defined

这是我的两个测试文件:

ES6 模块

import Library from 'some-library';

export const person = { firstName: "Bob", lastName: "Mortimer };

CommonJS 模块

const Library = require('some-library');

const person = { firstName: "Bob", lastName: "Mortimer };
module.exports.person = person;

因此,我尝试使用两个不同的二进制文件 -generator用于 ES6 模块和generator-cjsCommonJS 模块 - 我修改了原始文件以使用requires 代替import,但是,bin/generator.mjs继续正常工作,但bin/generator.cjs抛出此错误:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: [...]/test-module.js
require() of ES modules is not supported.
require() of [...]/test-module.js from [...]/bin/generator.cjs is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename test-module.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from [...]/package.json.

如果我"type": "module"从我的package.json,中删除generatorgenerator-cjs处理 CommonJS 文件,但generator在 ES6 模块上抛出此错误:

throw new Error('Unexpected import statement in CJS module.');
            ^
Error: Unexpected import statement in CJS module.

理想情况下:我想要一个可以动态导入 CommonJS 和 ES6 模块的二进制文件。

如果您已经阅读到这里 - 谢谢。

您对我如何解决此问题有任何想法吗?如果您希望我尝试提供更多信息,请告诉我。

谢谢,


编辑:我应该提一下,将 CommonJS 模块转换为 ES6 不是一种选择,因为有近一百个 CJS 模块,并且它们具有复杂的依赖链,需要时间来解开。

4

0 回答 0