我正在为 Web 应用程序编写测试套件,并且需要将 JSX 从源导入到测试环境中。此过程的一部分用于@babel/register将我的 JSX 正确转换为标准 JS。我的 babel 配置如下所示:
{
"presets": ["@babel/preset-env"],
"plugins": [
"@babel/plugin-syntax-jsx",
["babel-plugin-transform-jsx-to-htm",{
"import": {
"module": "htm/preact",
"export": "html"
},
"tag": "$$html"
}]
]
}
Run Code Online (Sandbox Code Playgroud)
我执行node -r @babel/register ...<unrelated test command here>
我遇到的问题是,当我的源文件之一从仅提供 ESM 输出而不提供 CJS 的库导入时。这是我遇到的错误:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: <file path to non-working ESM module>
require() of ES modules is not supported.
require() of <file path to non-working ESM module> from <file path to source that imports it> 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 <esm file>.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from <file path to non-working ESM module>/package.json.
at Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
at Object.newLoader [as .js] (/home/ryun/Projects/foobar/node_modules/pirates/lib/index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (<file path to source that imports it>.jsx:1:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Module._compile (/home/ryun/Projects/foobar/node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
Run Code Online (Sandbox Code Playgroud)
在 的文档页面底部@babel/register,它指出:Note: @babel/register does not support compiling native Node.js ES modules on the fly, since currently there is no stable API for intercepting ES modules loading.因此,我认为这@babel/register是不行的,但没有提供解决方法。除了为了我的测试套件硬分叉我正在使用的库并让它导出 CJS 之外,我不知道我应该在那里做什么。