复制antlr4ts代码运行测试遇Babel装饰器错误,求配置方案
解决Babel处理装饰器时的"Computed method/property decorators are not yet supported"错误
问题分析
你遇到的错误是Babel处理类属性装饰器时的兼容性问题,核心原因是插件配置重复、顺序错误,以及TypeScript装饰器语法未正确启用。
具体修复步骤
1. 精简Babel配置,移除重复插件
你的.babelrc.json中主配置和test环境重复添加了@babel/plugin-syntax-decorators,这个插件是多余的——@babel/plugin-proposal-decorators已经包含了装饰器的语法解析能力,重复添加会导致冲突。修改后的配置示例(若test环境配置与主配置完全一致,可直接删除env.test节点减少冗余):
{ "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ], "@babel/preset-typescript" ], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ], [ "@babel/plugin-proposal-class-properties", { "loose": true } ], "babel-plugin-parameter-decorator", [ "@babel/plugin-transform-destructuring", { "useBuiltIns": true } ], "@babel/plugin-transform-runtime" ], "env": { "test": { "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ], "@babel/preset-typescript" ], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ], [ "@babel/plugin-proposal-class-properties", { "loose": true } ], "babel-plugin-parameter-decorator", [ "@babel/plugin-transform-destructuring", { "useBuiltIns": true } ], "@babel/plugin-transform-runtime" ] } } }
2. 严格保证插件顺序
Babel插件按从左到右顺序执行,必须让@babel/plugin-proposal-decorators排在@babel/plugin-proposal-class-properties之前——装饰器需要先完成解析,才能正常处理类属性。
3. 启用TypeScript装饰器语法
在项目根目录的tsconfig.json中添加或修改以下配置:
{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, // 保留其他已有配置... } }
antlr4ts大量使用装饰器语法,TypeScript必须明确允许编译这类语法。
4. 确保依赖版本兼容
保证Babel相关依赖版本匹配,执行以下命令更新到兼容版本:
npm install @babel/core@latest @babel/preset-env@latest @babel/preset-typescript@latest @babel/plugin-proposal-decorators@latest @babel/plugin-proposal-class-properties@latest --save-dev
验证修复
修改完成后重新执行jz test,即可正常处理antlr4ts中的装饰器代码,不再触发该语法错误。
内容的提问来源于stack exchange,提问作者hehe123456
相关产品推荐
相关产品推荐

