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

如何在Vite中测试支持装饰器的esbuild v0.21.0版本?

在Vite中指定使用esbuild v0.21.0并测试装饰器提案特性

1. 强制Vite使用esbuild v0.21.0

Vite默认捆绑了特定版本的esbuild,要替换为v0.21.0,需通过包管理器强制覆盖依赖:

  • npm:在package.json中添加overrides字段:
{
  "overrides": {
    "esbuild": "0.21.0"
  }
}

执行npm install生效

  • Yarn:在package.json中添加resolutions字段:
{
  "resolutions": {
    "esbuild": "0.21.0"
  }
}

执行yarn install生效

  • pnpm:在package.json中添加pnpm.overrides字段:
{
  "pnpm": {
    "overrides": {
      "esbuild": "0.21.0"
    }
  }
}

执行pnpm install生效

2. 配置Vite启用装饰器提案特性

在vite.config.js中,通过esbuild选项开启装饰器的提案支持:

import { defineConfig } from 'vite'

export default defineConfig({
  esbuild: {
    tsconfigRaw: {
      compilerOptions: {
        experimentalDecorators: true,
        emitDecoratorMetadata: true
      }
    }
  }
})

若项目使用TypeScript,需同步修改tsconfig.json的对应配置:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
    // 其他原有配置...
  }
}

3. 验证配置是否生效

写一段简单的装饰器测试代码:

function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function(...args: any[]) {
    console.log(`调用 ${propertyKey},参数:`, args);
    return originalMethod.apply(this, args);
  };
  return descriptor;
}

class TestClass {
  @Log
  greet(name: string) {
    return `Hello, ${name}!`;
  }
}

const instance = new TestClass();
instance.greet('World'); // 控制台应打印调用日志

运行Vite项目后查看控制台输出,同时可执行以下命令确认esbuild版本:

npm ls esbuild

输出需显示版本为0.21.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:17:07