reactjstypescriptvitetypescript-decoratorvite-reactjs

React Vite Typescript version 5 can't use new decorators


I created new React Typescript app using vite

I executed npm create vite@latest then selected typescript-swc

I can't get why I can not use the new decorators

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()

This is the code I am trying to execute

I can't execute this without setting tsDecorators: true in the vite config plugin from @vitejs/plugin-react-swc. It is the only plugin I have, nothing more in the vite config.

console.log(context) logs the method name greet as a string, just like the old decorators, but it should be object. replacementMethod does not get called at all

I haven't set experimentalDecorators in tsconfig.ts

Why decorators work like the ones from version 4, instead of 5?


Solution

  • Vite uses esbuild, and esbuild as of 18.17 does not yet support compiling the new decorator format. It can read and understand such decorators, but doesn't know how to generate code for them yet.

    So if you want to use decorators with esbuild, you have to use the old kind for now. (You would have to use babel or Typescript to compile your code instead of esbuild if you want the new decorators without needing to wait for the esbuild upgrade.)