React Vite Typescript 版本 5 无法使用新的装饰器

Okt*_*can 6 typescript reactjs typescript-decorator vite vite-reactjs

我使用 vite 创建了新的 React Typescript 应用程序

我执行npm create vite@latest然后选择typescript-swc

  • package.json 中的 Typescript 版本为 ^5.0.2
  • node_modules/typescript/package.json 中的版本是 5.1.3
  • 我的全球版本是5.1.3

我不明白为什么我不能使用新的装饰器

function loggedMethod(originalMethod: any, context: ClassMethodDecoratorContext) {
  console.log(context)
  const methodName = String(context.name)
  function replacementMethod(this: any, ...args: any[]) {
      console.log(`LOG: Entering method '${methodName}'.`)
      const result = originalMethod.call(this, ...args)
      console.log(`LOG: Exiting method '${methodName}'.`)
      return result
  }
  return replacementMethod
}

class Person {
  name: string

  constructor(name: string) {
      this.name = name
  }

  @loggedMethod
  greet() {
      console.log(`Hello, my name is ${this.name}.`)
  }
}
const p = new Person('Ray')
p.greet()
Run Code Online (Sandbox Code Playgroud)

这是我试图执行的代码

tsDecorators: true如果不从 .vite 配置插件中进行设置,我将无法执行此操作@vitejs/plugin-react-swc。这是我唯一的插件,vite 配置中没有其他插件。

console.log(context)将方法名称记录greet为字符串,就像旧的装饰器一样,但它应该是对象。replacementMethod根本没有被叫到

我还没有设置experimentalDecorators进去tsconfig.ts

为什么装饰器的工作方式与版本 4 中的类似,而不是版本 5 的?

PJ *_*Eby 4

Vite 使用 esbuild,esbuild 从 18.17 开始还不支持编译新的装饰器格式。它可以读取和理解此类装饰器,但还不知道如何为它们生成代码。

所以如果你想在 esbuild 中使用装饰器,你现在必须使用旧的装饰器。(如果您想要新的装饰器而不需要等待 esbuild 升级,则必须使用 babel 或 Typescript 来编译代码而不是 esbuild。)