![](/img/trans.png)
[英]How to set up Jest w/ESM to recognize non-cjs modules in node_modules
[英]Transpile validator esm node_modules files jest
我正在使用带有可摇树 esm 导入的验证器库,以实现有效的包大小。
当我尝试使用 jest 测试使用 esm 模块导入的文件时,我收到以下错误 -
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
helpers/node_modules/validator/es/lib/isEmpty.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import assertString from './util/assertString';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import isEmpty from 'validator/es/lib/isEmpty';
| ^
2 | import isURL from 'validator/es/lib/isURL';
3 | import isEmail from 'validator/es/lib/isEmail';
4 | import matches from 'validator/es/lib/matches';
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/validator.ts:1:1)
现在我知道 jest 无法解析 ESM 模块,所以我尝试将验证器库添加到transformIgnorePatterns
。 这就是我的 jest.config.js 的样子
module.exports = {
preset: 'ts-jest',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
transformIgnorePatterns: ['<rootDir>/node_modules/(?!(validator/es/lib)/)'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
};
但这没有用。
我也尝试了这个答案并添加了 babel 进行编译,答案中提到了相同的配置,但我仍然遇到同样的错误。
尽管测试适用于非 ESM 导入,例如,
import isEmpty from 'validator/lib/isEmpty';
尝试将此行添加到您的jest.config.js
module.exports = {
...
transformIgnorePatterns: [
'/node_modules/(?!(validator)/)'
],
...
}
或尝试从package.json
更新玩笑
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!(validator)/)"
]
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.