You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Babel配置迁移至SWC遇MobX装饰器问题求助

Babel 迁移至 SWC 配置问题

原项目使用的 Babel 配置:

module.exports = {
  sourceMaps: true,
  presets: [
    [
      '@babel/preset-env',
      {
        exclude: ['transform-async-to-generator', 'transform-regenerator'],
      },
    ],
    '@babel/preset-react',
    [
      '@babel/preset-typescript',
      {
        isTSX: true,
        allExtensions: true,
      },
    ],
  ],
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    ['module:fast-async', { spec: true }],
    [
      '@babel/plugin-transform-regenerator',
      {
        asyncGenerators: true,
        generators: true,
        async: false,
      },
    ],
  ],
};

我自行编写了 SWC 配置,但应用后部分功能失效,出现错误:[MobX] Cannot decorate undefined property: 'description'
当前 SWC 配置:

test: /\.(tsx|ts|jsx|js)$/,
loader: 'swc-loader',
options: {
  jsc: {
    keepClassNames: true,
    parser: {
      syntax: 'typescript',
      decorators: true,
      tsx: true,
      dynamicImport: true,
      preserveAllComments: false
    },
    transform: {
      legacyDecorator: true,
      decoratorMetadata: true
    },
    loose: false
  },
},

修正后的 SWC 配置方案

针对问题,需对齐原 Babel 配置的所有特性,调整后的 SWC 配置如下:

test: /\.(tsx|ts|jsx|js)$/,
loader: 'swc-loader',
options: {
  sourceMaps: true, // 匹配原Babel的sourceMaps配置
  jsc: {
    keepClassNames: true,
    parser: {
      syntax: 'typescript',
      decorators: true,
      tsx: true,
      dynamicImport: true,
      preserveAllComments: false
    },
    transform: {
      react: {
        runtime: 'automatic' // 对应@babel/preset-react默认行为,原项目用classic则改为该值
      },
      legacyDecorator: true,
      decoratorMetadata: true,
      classProperties: {
        loose: true // 对齐原Babel的class-properties loose模式,解决MobX装饰器错误核心配置
      }
    },
    loose: false,
    target: 'es2015', // 对应@babel/preset-env的目标环境,可按需调整
    exclude: [
      'transform-async-to-generator',
      'transform-regenerator' // 匹配原Babel preset-env的排除项
    ],
    transpile: {
      asyncGenerators: true,
      generators: true,
      async: false // 对应原Babel的transform-regenerator配置
    }
  }
},

关键配置说明

  • classProperties.loose: 设置为true,原Babel用松散模式处理类属性,SWC默认严格模式会导致MobX装饰器无法识别类属性,这是解决当前错误的核心
  • sourceMaps: 开启源码映射,和原Babel配置保持一致
  • transpile配置: 同步原Babel对生成器函数的转换规则,开启生成器支持但关闭async转换
  • exclude: 移除原Babel排除的两个转换插件
  • React转换: 默认使用automatic runtime,若原项目Babel配置指定了runtime: 'classic',需同步修改SWC对应配置

内容的提问来源于stack exchange,提问作者Котик Вася

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:25:19