问题描述
我在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;
因此,我然后尝试使用两个不同的二进制文件-用于ES6模块的generator
和用于CommonJS的generator-cjs
-我将原始文件修改为使用require
代替{{1} },但是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
和generator
都可以在CommonJS文件上使用,但是generator-cjs
会在ES6模块上抛出此错误:
generator
理想情况::我想拥有一个可以动态导入CommonJS和ES6模块的二进制文件。
如果您已经读完这本书,谢谢。
您对我该如何解决有任何想法?如果您要我尝试提供更多信息,请告诉我。
谢谢
编辑:我要提到的是,将CommonJS模块转换为ES6并不是一种选择,因为有将近一百个CJS模块,并且它们具有复杂的依赖链,需要花费一些时间才能弄清。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)