如何为类方法装饰器生成元数据

解读

这道题考察的是“装饰器 + 元数据”两条链路的 Babel 编译落地能力。
国内一线厂(蚂蚁、字节、美团)的面试里,高频追问点有三:

  1. 装饰器语法目前仍处于 Stage 3,Babel 侧如何开关插件;
  2. 元数据(design:type、design:paramtypes、design:returntype)并非 ECMA 规范,而是 reflect-metadata 提案的副产品,Babel 怎样“零成本”地注入;
  3. 产物要在 Node 14+ 及低端浏览器同时跑通,如何配 preset、polyfill、helper 导入路径,避免把 reflect-metadata 打爆包体。
    一句话:让装饰器“能跑”只是及格,让元数据“按需、精准、可tree-shaking”才是加分。

知识点

  1. 装饰器编译链路
    @babel/plugin-proposal-decorators 的两种实现:
    • legacy:2018 之前的旧语义,与 metadata 深度耦合,国内老项目存量大;
    • 2023-03:新语义,class 字段先初始化再装饰,metadata 需手动开启。
  2. 元数据生成链路
    @babel/plugin-proposal-decorators 的 decoratorsBeforeExport 与 version 选项组合后,若再加 @babel/plugin-proposal-class-properties 与 @babel/plugin-transform-typescript,可自动在方法/属性/参数三处插入 __metadata(k, v) 调用。
  3. helper 与 polyfill 策略
    • 使用 @babel/runtime + @babel/plugin-transform-runtime,把 __metadata 指向 import { __metadata } from "@babel/runtime/helpers/esm/metadata",避免重复;
    • reflect-metadata 本身 50 KB,不能全量打包,需 babel-plugin-polyfill-corejs3 的 exclude: ['reflect-metadata'] 或 usage-pure 模式,让业务自己 import 'reflect-metadata' 一次即可。
  4. TypeScript 联动
    tsconfig 里 experimentalDecorators 与 emitDecoratorMetadata 必须双开;Babel 侧若走 preset-typescript,需把 onlyRemoveTypeImports: true,否则类型擦除会提前干掉类型节点,导致 metadata 收集不到。
  5. 产物验证
    用 @babel/standalone 在线编译,看是否生成
    __decorate([
      __metadata("design:type", Function),
      __metadata("design:paramtypes", [String, Number]),
      __metadata("design:returntype", void 0)
    ], Foo.prototype, "bar", null);
    
    若缺失,则检查 plugins 顺序:decorators 必须在 class-properties 之前,typescript preset 必须在最前。

答案

  1. 安装依赖
    npm i -D @babel/core @babel/preset-env @babel/preset-typescript \
            @babel/plugin-proposal-decorators@^7.21.0 \
            @babel/plugin-transform-runtime \
            @babel/runtime-corejs3 reflect-metadata
    
  2. 配置 .babelrc.js(以 2023-03 新语义为例,若公司代码库仍用 legacy,把 version 改 "legacy": true 即可)
    module.exports = {
      presets: [
        ['@babel/preset-env', { targets: { node: 14, chrome: 58 }, modules: false }],
        ['@babel/preset-typescript', { onlyRemoveTypeImports: true }]
      ],
      plugins: [
        ['@babel/plugin-proposal-decorators', { version: '2023-03', decoratorsBeforeExport: true }],
        ['@babel/plugin-proposal-class-properties', { loose: true }],
        ['@babel/plugin-transform-runtime',
          { corejs: 3, helpers: true, regenerator: true, useESModules: true }]
      ]
    };
    
  3. 入口文件顶部一次性引入 reflect-metadata
    import 'reflect-metadata';
    
  4. 写装饰器并验证
    function log(target: any, key: string, desc: PropertyDescriptor) {
      const fn = desc.value;
      desc.value = function (...args: any[]) {
        console.log(`调用 ${key}`);
        return fn.apply(this, args);
      };
    }
    
    class Demo {
      @log
      add(a: string, b: number): void {
        console.log(a, b);
      }
    }
    
    const meta = Reflect.getMetadata('design:paramtypes', Demo.prototype, 'add');
    console.log(meta); // [String, Number]
    
  5. 打包后体积优化
    在 babel-loader 加 cacheDirectory: true,并用 webpack-bundle-analyzer 确认 reflect-metadata 只出现一次;若出现两份,检查是否把 @babel/runtime-corejs3 与 core-js-pure 混用,统一成同一套 polyfill 方案即可。

拓展思考

  1. 如果未来装饰器进入 Stage 4,Babel 会移除 legacy 支持,老项目如何“无痛”迁移?
    答:可写一条 Babel 插件链,先 babel-plugin-codemod-decorators-legacy-to-2023 把语法树批量改写成新语义,再跑单元测试;元数据部分因为 API 不变,只需把 __metadata 调用保留即可。
  2. 元数据只能描述类型吗?能否注入自定义业务标记?
    答:可以。在装饰器里手动 Reflect.defineMetadata('custom:role', 'admin', target, key),配合 import 'reflect-metadata' 即可;Babel 侧无需额外插件,但要保证该装饰器在运行时执行,因此不能全量擦除。
  3. 微前端场景下,子应用 A、B 都带 reflect-metadata,如何避免全局污染?
    答:用 importMaps 或 SystemJS 的 singleton 字段,把 reflect-metadata 提升到基座应用;子应用通过 __webpack_require__.shared 复用同一份 Reflect 对象,确保元数据命名空间全局唯一,防止重复挂载导致 design:paramtypes 被覆盖。