我正在使用 validator library with tree-shakable esm imports有效的捆绑尺寸。
当我尝试使用 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'],
};
但这没有用。
我也试过this answer并添加了用于转译的 babel,使用答案中提到的相同配置,但我仍然遇到相同的错误。
尽管测试适用于 non-ESM imports ,喜欢,
import isEmpty from 'validator/lib/isEmpty';
最佳答案
尝试将此行添加到您的 jest.config.js
module.exports = {
...
transformIgnorePatterns: [
'/node_modules/(?!(validator)/)'
],
...
}
或尝试从 package.json
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!(validator)/)"
]
},
关于javascript - Transpile 验证器 esm node_modules 文件 jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66711530/