如何配置ESLint支持TypeScript装饰器语法

解读

国内一线/二线厂的前端面试里,TypeScript 装饰器(Decorator)几乎是“必踩坑”——项目里大量用(如 NestJS、Angular、Midway、Egg 插件),但 CI 一跑就报 Parsing error: Unexpected character @。
面试官真正想验证的是:

  1. 你是否清楚 ESLint 的解析链路(Parser → Plugin → Rule);
  2. 能否把“语法支持”与“规则校验”拆开处理,而不是网上抄一段配置就完事;
  3. 是否了解 2022 之后国内主流项目已全面迁移 @typescript-eslint v5+,旧答案(parserOptions.ecmaVersion + experimentalDecorators)已不够。
    答不到“parser 与 plugin 版本对齐、project 选项、规则冲突”这三点,基本会被追问到挂。

知识点

  1. ESLint 默认使用 espree,只能解析 ECMAScript 最新 Stage-4 语法;装饰器仍是 Stage-3,必须换 @typescript-eslint/parser。
  2. @typescript-eslint/parser 依赖 TypeScript Compiler API,因此:
    • 必须同时安装 @typescript-eslint/eslint-plugin;
    • 必须提供 tsconfig.json 路径(parserOptions.project),否则无法做类型检查级规则。
  3. 装饰器语法开关:
    • tsconfig.json 里 "experimentalDecorators": true 决定 TSC 是否放行;
    • ESLint 侧无需再开 ecmaVersion: 2022 之类,parser 会自动跟随 TSC。
  4. 规则冲突:
    • @typescript-eslint/no-unused-vars 与 no-unused-vars 重复;
    • @typescript-eslint/no-parameter-properties 与装饰器参数属性写法冲突;
    • no-undef 对装饰器注入的元数据字段误报。
      国内规范模板(阿里、字节、美团)统一关掉基座规则,用插件扩展规则。
  5. 版本对齐:@typescript-eslint 与 TypeScript 版本必须官方兼容矩阵,国内镜像源(npmmirror)常缓存旧包,lock 文件易踩坑。
  6. 性能:CI 中若项目过大,需加 parserOptions.tsconfigRootDir 与 EXPERIMENTAL_useSourceOfProjectReferenceRedirect 降低 30%+ 扫描耗时,否则会被运维吐槽。

答案

  1. 安装对齐版本(以 TS 5.2 为例)

    pnpm add -D eslint @typescript-eslint/{parser,eslint-plugin}@^6.0.0
    

    确保 lock 文件解析到同一镜像源,避免国内缓存漂移。

  2. 配置 tsconfig.json

    {
      "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "target": "ES2022",
        "module": "commonjs",
        "esModuleInterop": true
      }
    }
    
  3. 配置 .eslintrc.js(国内团队普遍用 JS 配置,方便动态拼接路径)

    module.exports = {
      root: true,
      // 1. 换 parser
      parser: '@typescript-eslint/parser',
      parserOptions: {
        ecmaVersion: 'latest', // 无需指定 2022,跟随 TSC
        sourceType: 'module',
        project: './tsconfig.json', // 必须指向真实路径
        tsconfigRootDir: __dirname,
      },
      // 2. 加载插件
      plugins: ['@typescript-eslint'],
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
        // 如团队有类型检查级规则
        'plugin:@typescript-eslint/recommended-requiring-type-checking',
      ],
      rules: {
        // 3. 解决冲突
        'no-unused-vars': 'off',
        '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
        'no-undef': 'off', // 装饰器注入字段会误报
      },
      // 4. 若用 Angular/Nest,关闭参数属性警告
      overrides: [
        {
          files: ['*.controller.ts', '*.service.ts'],
          rules: {
            '@typescript-eslint/no-parameter-properties': 'off',
          },
        },
      ],
    };
    
  4. 验证

    npx eslint src/**/*.ts
    

    装饰器语法不再报 Parsing error,且 @Injectable() 等元数据不会触发 no-undef。

  5. CI 加速(可选,国内 GitLab Runner 4C8G 场景)

    script:
      - EXPERIMENTAL_useSourceOfProjectReferenceRedirect=true pnpm eslint --cache --cache-strategy content .
    

拓展思考

  1. 如果项目同时有 Babel 链(如 Next.js SWC),Babel 的 plugin-proposal-decorators 与 TSC 的 experimentalDecorators 语法不一致,ESLint 该用哪个 parser?
    答:ESLint 只认最终交给它的源码,只要构建链保证运行时代码正确,parser 仍选 @typescript-eslint/parser;但需把 babel.config.js 的 legacy: true 与 TSC 对齐,否则会出现“编译能过、ESLint 报语法错”的诡异现象。

  2. 装饰器元数据反射依赖 reflect-metadata,在 ESLint 里如何防止 import/no-extraneous-dependencies 误报?
    答:在 .eslintrc 里加

    settings: {
      'import/core-modules': ['reflect-metadata']
    }
    

    或直接在 rule 里 import/no-extraneous-dependencies: ['error', { devDependencies: false, optionalDependencies: false, peerDependencies: false }]

  3. 未来装饰器进 Stage-4 后,ESLint 原生 parser 会支持吗?
    答:espree 跟进节奏通常滞后 1-2 个版本,国内项目为了类型检查级规则,仍会长期留在 @typescript-eslint 链路;届时只需移除 experimentalDecorators 开关,无需调整 ESLint 配置,实现“零配置迁移”。