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

为什么Vite环境下使用reflect-metadata获取design:paramtypes返回undefined

问题原因

Vite开发环境默认采用esbuild对TypeScript代码做转译处理,而esbuild本身不支持emitDecoratorMetadata特性,即便你在tsconfig.json中开启了experimentalDecorators和emitDecoratorMetadata配置,esbuild也不会生成装饰器相关的元数据代码,所以会导致Reflect.getMetadata("design:paramtypes", target)返回undefined。

注意:请确保import 'reflect-metadata'写在项目入口文件的最顶部,早于所有使用装饰器的代码加载,否则也会出现元数据读取失败的问题。

解决方案

你可以根据自己的项目需求选择以下任意一种方案解决:

方案1:配合Babel插件转译(兼容性最优)

该方案关闭esbuild的TS转译能力,改用Babel处理装饰器元数据生成:

  • 修改vite.config.ts配置,关闭esbuild转译:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  esbuild: false
})
  • 安装所需依赖:
npm install @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties babel-plugin-transform-typescript-metadata -D
  • 项目根目录新增babel.config.json配置文件:
{
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "version": "legacy" }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

方案2:使用TSC转译插件(配置最简)

直接引入Vite的TSC转译插件,用官方TSC处理代码,自动保留装饰器元数据:

  • 安装依赖:
npm install vite-plugin-tsc -D
  • 修改vite.config.ts配置:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tsc from 'vite-plugin-tsc'

export default defineConfig({
  plugins: [react(), tsc()]
})

内容的提问来源于stack exchange,提问作者januw a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 23:36:00