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

Webpack + ts-loader处理Stage 3装饰器报错:意外字符'@'

问题排查:Webpack + ts-loader 下 TypeScript 5 Stage 3 装饰器编译报错

问题描述

以下TypeScript代码使用了Stage 3装饰器提案语法:

const decorator = (constructor: any, _context: any) => constructor

@decorator
export class Decorated {}

在Webpack + ts-loader环境下编译失败,报错信息为:Unexpected character '@'。相关Webpack配置片段:

rules: [
    {
        test: /\.ts$/,
        use: "ts-loader",
        resolve: {
            extensionAlias: {
                ".js": [".ts"]
            }
        }
    }
]

启用experimentalDecorators后可识别旧版装饰器语法,但TypeScript 5已支持新版Stage 3装饰器,仍出现该报错。

排查步骤及解决方案

1. 修正tsconfig.json配置

TypeScript 5的Stage 3装饰器与旧版实验性装饰器不能共存,需确保以下配置:

  • 设置experimentalDecorators为false(必须关闭旧版装饰器支持)
  • 启用decoratorsBeforeExport为true(可选,适配装饰器在export前的语法)
  • target设置为ES2022或更高版本(新装饰器依赖ES2022+语法特性)
  • module建议设置为ESNext或NodeNext以匹配新装饰器的模块解析逻辑

示例tsconfig配置片段:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "experimentalDecorators": false,
    "decoratorsBeforeExport": true,
    "strict": true
  }
}

2. 升级ts-loader至兼容版本

旧版ts-loader可能未适配TypeScript 5的新装饰器语法,需升级ts-loader到最新稳定版,确保其与当前TypeScript版本兼容(建议ts-loader@20.x+搭配TypeScript 5.x)。

升级命令:

npm install ts-loader@latest --save-dev
# 或
yarn add ts-loader@latest --dev

3. 验证TypeScript独立编译

先跳过Webpack,直接用tsc命令编译代码,确认是否能正常输出:

npx tsc

如果tsc编译成功,说明问题出在Webpack与ts-loader的适配;如果tsc也报错,优先检查tsconfig配置是否符合新装饰器的要求。

4. 检查Webpack loader执行顺序

确保ts-loader是处理.ts文件的唯一loader,没有其他loader(如babel-loader)在ts-loader之前处理文件,导致装饰器语法被提前解析报错。


内容的提问来源于stack exchange,提问作者Jeroen Knoef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:33:13