已成功设置 jest/esm,但偶尔会发布一个模块,同时指定 main
key (用于 commonjs)和 module
package.json
中的 key (对于 ESM) .这会导致 Jest 错误,例如 uuid module :
/repo/path/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
我可以看到 dist/esm-browser/index.js
是module
指定的文件输入 package.json
.如何配置 Jest w/ESM 来处理这些情况,其中 node_modules 中的东西是 ESM?
Jest 配置:
{
"resetMocks": true,
"testEnvironment": "jsdom",
"testMatch": [
"**/src/**/*.(spec|test).[tj]s?(x)"
],
"preset": "ts-jest/presets/default-esm",
"extensionsToTreatAsEsm": [
".ts",
".tsx"
],
"globals": {
"ts-jest": {
"useESM": true
}
},
"globalSetup": "<rootDir>/jest/setup.cjs",
"globalTeardown": "<rootDir>/jest/teardown.cjs",
"watchPathIgnorePatterns": [
"<rootDir>/.tmp"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/src/$1",
"^~components/(.*)$": "<rootDir>/src/components/$1",
"^~util/(.*)$": "<rootDir>/src/util/$1",
"^~types/(.*)$": "<rootDir>/src/types/$1"
}
}
最佳答案
我遇到了同样的问题,并且修复方法与此评论中提到的相同:https://github.com/nrwl/nx/issues/812#issuecomment-429420861在我的jest.config.js
:
// list to add ESM to ignore
const esModules = ['uuid'].join('|');
// ...
module.exports = {
//...
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
// ...
};
关于javascript - 如何设置 Jest w/ESM 以识别 node_modules 中的非 cjs 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72163561/