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

CRA集成Inversify时@inject装饰器报Unexpected character '@'错误

报错根因说明

  1. 构造函数参数装饰器识别失败:你仅在test环境配置了参数装饰器解析插件,开发/生产环境没有加载对应插件,无法识别构造函数参数上的@inject装饰器。
  2. TYPES提前初始化报错:一方面是tsconfig关闭了装饰器元数据输出,另一方面可能存在模块导入顺序问题或者装饰器使用逻辑错误。

解决方案

1. 调整babel配置

将babel-plugin-parameter-decorator移到全局plugins数组,注意调整插件加载顺序,正确的全局插件配置如下:

{
  "presets": [
    ...,
    "@babel/preset-typescript"
  ],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    // 新增到全局,放在装饰器提案插件之前
    "babel-plugin-parameter-decorator",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ],
  "env": {
    "test": {
      "plugins": [
        "transform-require-context",
        "babel-plugin-transform-typescript-metadata",
        "babel-plugin-parameter-decorator"
      ]
    }
  }
}

2. 调整tsconfig配置

开启装饰器元数据输出,DI框架依赖该能力读取注入类型:

{
  "compilerOptions": {
    ...,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true // 配置缺失的话也补上,开启装饰器基础支持
  },
}

3. 修正注入代码逻辑

你当前代码同时使用了参数注入和手动拉取依赖,冗余且容易出错,修正为:

class DefaultTodoApiProvider implements TodoApiProvider {
  private httpClient: HttpClient;

  constructor(@inject(TYPES.HttpClient) httpClient: HttpClient) {
    // 直接使用注入的实例,无需重复调用Dependency.get
    this.httpClient = httpClient;
  }

  async getTodoById(id: string) {
    const data = await this.httpClient.get(
      `https://jsonplaceholder.typicode.com/todos/${id}`
    );
    return data;
  }
}

decorate(injectable(), DefaultTodoApiProvider);
export default DefaultTodoApiProvider;

4. 解决TYPES初始化报错(如果仍需要使用属性装饰器)

确认TYPES的导入语句放在当前文件最顶部,排查是否存在TYPES所在模块和当前文件的循环依赖问题。


内容的提问来源于stack exchange,提问作者Alan Yong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:15:07