TypeScript 5.0正式装饰器在Jest中报语法错误的解决方法咨询
解决Jest解析TypeScript 5.0正式装饰器的配置问题
问题背景
使用TypeScript 5.0正式装饰器编写代码时,Jest遇到@符号会抛出SyntaxError: Invalid or unexpected token错误,现有配置如下:
现有jest.config.js
module.exports = { preset: 'ts-jest', transform: { '^.+\\.(ts|tsx)?$': ['ts-jest', { tsConfig: 'tsconfig.esm.json' }], "^.+\\.(js|jsx)$": "babel-jest", } };
现有tsconfig.esm.json
{ "compilerOptions": { "module": "esnext", "target": "esnext", "outDir": "dist/esm", "declaration": true, "declarationMap": true, "declarationDir": "dist/types", "sourceMap": true, "strict": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "moduleResolution": "nodenext", "baseUrl": ".", "paths": { "*": ["src/*"] } }, "include": ["src/*.ts","src/**/*.ts", "test/*.ts"], "exclude": ["node_modules"] }
现有babel.config.js
module.exports = {presets: ['@babel/preset-env']}
解决方案
需要调整三个配置文件,确保TypeScript和Jest都能正确识别正式装饰器语法:
1. 更新tsconfig.esm.json,启用标准装饰器支持
在compilerOptions中添加或修改以下配置,开启TypeScript 5.0的正式装饰器支持:
{ "compilerOptions": { // 保留原有配置 "experimentalDecorators": false, // 关闭旧版实验性装饰器,启用正式标准装饰器 "emitDecoratorMetadata": true, // 可选:需要反射元数据时开启 "decoratorsBeforeExport": true // 可选:根据装饰器位置调整,true表示装饰器写在export前(@Decorator export class ...) }, // 保留原有include/exclude配置 }
2. 修改jest.config.js,适配ESM和新装饰器
调整ts-jest的预设和配置,确保它能处理ESM模块和新装饰器语法:
module.exports = { preset: 'ts-jest/presets/default-esm', // 使用ESM兼容的预设 transform: { '^.+\\.(ts|tsx)?$': ['ts-jest', { tsConfig: 'tsconfig.esm.json', useESM: true // 启用ESM模式 }], "^.+\\.(js|jsx)$": "babel-jest", }, extensionsToTreatAsEsm: ['.ts', '.tsx'] // 将TS文件视为ESM模块 };
3. 调整babel.config.js(若JS文件也使用装饰器)
如果你的JS代码也用到了装饰器,需要添加Babel插件支持标准装饰器:
首先安装依赖:
npm install --save-dev @babel/plugin-proposal-decorators
然后修改配置:
module.exports = { presets: ['@babel/preset-env'], plugins: [ ['@babel/plugin-proposal-decorators', { version: '2023-07' }] // 指定使用2023年标准装饰器语法 ] };
额外注意事项
- 确保TypeScript版本在5.0及以上,ts-jest版本使用v29及以上(需兼容TypeScript 5.0)
- 若不需要处理JS文件的装饰器,可跳过第三步的Babel配置调整
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

