如何配置ESLint支持装饰器语法
解读
国内前端项目普遍采用 TypeScript + Babel 双轨编译,装饰器(Decorator)在 Angular、NestJS、Midway 等框架中属于“刚需”。
面试官问这道题,并不是想听你背文档,而是考察三点:
- 是否清楚 ESLint 默认解析器(Espree)与装饰器语法不兼容;
- 能否把 parser、parserOptions、plugin、rule 四条线一次说全,避免“改完 parser 就完事”的初级错误;
- 是否具备落地经验:如何兼顾 VS Code 实时报错、Git Hooks 卡点、CI 缓存提速,让团队零感知切换。
知识点
- 语法兼容链:Espree → @typescript-eslint/parser → @babel/eslint-parser,三者对装饰器的支持度依次递增。
- parserOptions.ecmaVersion 必须 ≥ 2022,且 decorator 相关插件要在 parser 层提前启用,否则规则层无法拿到正确 AST。
- 规则层:@typescript-eslint/eslint-plugin 提供 @typescript-eslint/no-unused-vars 等“装饰器感知”规则;eslint-plugin-decorator-position 可强制排序;eslint-plugin-import 的 import/no-unused-modules 在装饰器注入场景下容易误报,需要同步调整。
- 配置优先级:.eslintrc.js > package.json > 共享配置包;国内大厂多通过 @company/eslint-config 统一下发,候选人需说明如何“继承 + 覆盖”而不破坏基线。
- 性能陷阱:parser 切换后,lint 时间可能翻倍;需开启 cache: true、并行 lint(eslint --max-warnings=0 --cache-location node_modules/.cache/eslint),并在 GitLab CI 里把 .cache 目录打 tar 包做缓存。
答案
“我会分四步完成,确保本地、Git Hooks、CI 三端表现一致。
第一步,换解析器。TypeScript 项目直接用 @typescript-eslint/parser,并在 parserOptions 里加 ecmaVersion: 'latest',sourceType: 'module';如果是纯 Babel 项目,则装 @babel/eslint-parser,同时创建 babel.config.js,把 @babel/plugin-proposal-decorators 的 version 设为 '2023-05'(与 Babel 8 默认对齐)。
第二步,显式告诉 ESLint 装饰器语法已启用。TypeScript 项目无需额外插件,@typescript-eslint/parser 已内置;Babel 项目要在 parserOptions.requireConfigFile: true,确保读取 babel.config.js。
第三步,打开规则。团队规范要求装饰器必须写在类声明正上方、不可空行,我通过 eslint-plugin-decorator-position 的规则 decorator-position/decorator-position: ['error', { property: 'above', printWidth: 120 }] 来卡位;同时把 @typescript-eslint/no-unused-vars 的 varsIgnorePattern 设为 '^_',避免注入的元数据变量被误杀。
第四步,固化到工程模板。把上述配置抽成 @myfe/eslint-config-decorator,发布到私有 Verdaccio,然后在项目里 extends: ['@myfe/eslint-config-decorator'] 即可。CI 阶段加一句 eslint . --cache --cache-strategy content,平均提速 40%。”
拓展思考
- 双解析器共存场景:微前端主应用用 TypeScript,子应用用 Babel,如何在根目录一份 .eslintrc.js 里按 overrides 字段做“子目录级”解析器切换?提示:overrides.files 匹配子目录,parser 和 parserOptions 可局部覆盖。
- 装饰器元数据反射:当使用 reflect-metadata 时,会在全局注入 Map,ESLint 无法静态分析,导致 no-undef 误报。你会选择全局注释 /* global Reflect */,还是通过 globals 字段集中声明?讨论两种方案的维护成本。
- 未来标准:TC39 已把装饰器推到 Stage 3,Babel 8 将默认启用新语法。如何设计一条“灰度切换”脚本,让 200+ 仓库在 1 小时内完成 parser 与规则双重升级,并保证回滚单命令可逆?