Alex Gibson 有一篇很棒的文章“使用 Mocha 和 esm 测试原生 ES 模块”。谢谢他。
我尝试在我的项目中使用带有原生 ES 模块支持的 mocha,但我遇到了 2 个不同的错误:
$ ./node_modules/mocha/bin/mocha --require esm './test/Util.test.js'
TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback was not specified.
at exports.importModuleDynamicallyCallback (internal/process/esm_loader.js:41:9)
at formattedImport (/.../node_modules/mocha/lib/esm-utils.js:6:23)
at Object.exports.requireOrImport (/.../node_modules/mocha/lib/esm-utils.js:23:14)
at Object.exports.loadFilesAsync (/.../node_modules/mocha/lib/esm-utils.js:33:34)
at Mocha.loadFilesAsync (/.../node_modules/mocha/lib/mocha.js:427:19)
...
Run Code Online (Sandbox Code Playgroud)
$ /usr/bin/node /.../node_modules/mocha/bin/mocha -r esm --ui bdd --reporter \
/.../PhpStorm/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js \
/.../test/Util.test.js
TypeError: Invalid host defined options
at formattedImport (/.../node_modules/mocha/lib/esm-utils.js:6:23)
at Object.exports.requireOrImport (/.../node_modules/mocha/lib/esm-utils.js:23:14)
at Object.exports.loadFilesAsync (/.../node_modules/mocha/lib/esm-utils.js:33:34)
at Mocha.loadFilesAsync (/.../node_modules/mocha/lib/mocha.js:427:19)
...
Run Code Online (Sandbox Code Playgroud) 所以经过几天或谷歌搜索并自己尝试一些不同的设置后,我无法修复此错误。
背景:我正在编写一个带有服务器端渲染的 React 应用程序。我曾经写过很多 React 应用程序,但只使用客户端渲染,但对于一个新项目,我决定尝试 SSR 并且它可以工作,直到我添加Formik到混合中,导入lodash-es. 在深入挖掘之后,似乎 ES 模块node_modules没有被“转译”,因此当服务器运行时它会崩溃,因为节点似乎无法导入它。这是错误:
$ cross-env NODE_ENV=development webpack --config webpack.config.js --mode=development
$ node dist/server.js
.../node_modules/lodash-es/isPlainObject.js:1
import baseGetTag from './_baseGetTag.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1018:16)
at Module._compile (node:internal/modules/cjs/loader:1066:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Module.require (node:internal/modules/cjs/loader:991:19)
at require (node:internal/modules/cjs/helpers:92:18)
at eval (webpack://@nesta-se/admin/external_%22lodash-es/isPlainObject%22?:1:18)
at Object.lodash-es/isPlainObject (/Users/benjamin/GitHub/nesta-admin/build/server.js:809:1)
at __webpack_require__ (/Users/benjamin/GitHub/nesta-admin/build/server.js:1077:32)
Run Code Online (Sandbox Code Playgroud)
我使用 Webpack 和 Babel 来转译我的代码。
babel.config.js
{
"presets": [ …Run Code Online (Sandbox Code Playgroud)