解决TypeScript Jest测试中的static-class-block错误
解决Jest运行antlr4ng时的静态类块语法错误
核心原因
antlr4ng@3.0.4的CommonJS产物使用了静态类块语法,而Jest默认会忽略node_modules目录下的包转译,即便你添加了Babel插件,也没对这个包生效。
解决方案
1. 调整Babel配置,指定转译antlr4ng
修改babel.config.js(或.babelrc),在测试环境中明确让Babel处理antlr4ng包:
module.exports = { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript' ], env: { test: { plugins: ['@babel/plugin-transform-class-static-block'], // 关键:让Babel转译antlr4ng include: [/node_modules\/antlr4ng/] } } };
2. 更新Jest配置,取消对antlr4ng的转译忽略
Jest默认跳过node_modules的转译,需要在jest.config.js中排除antlr4ng:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', transformIgnorePatterns: [ // 不忽略antlr4ng,允许它被Babel转译 '/node_modules/(?!antlr4ng)' ] };
3. 清理Jest缓存
旧缓存可能导致配置不生效,执行以下命令清空缓存:
jest --clearCache
备选方案:使用antlr4ng的ES模块版本
如果上述方案无效,可以尝试直接使用ES模块版本:
- 在
tsconfig.json中设置模块解析策略为bundler或node16:{ "compilerOptions": { "moduleResolution": "bundler", "module": "ESNext" } } - 或者直接导入ES模块文件:
import * as antlr4ng from 'antlr4ng/dist/index.esm.js';
内容的提问来源于stack exchange,提问作者JimPri
相关产品推荐
相关产品推荐

