React Vite Typescript version 5 can't use new decorators
Asked Answered
H

1

7

I created new React Typescript app using vite

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

  • Typescript version in package.json is ^5.0.2
  • The version in node_modules/typescript/package.json is 5.1.3
  • My global version is 5.1.3

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?

Halvaard answered 14/6, 2023 at 9:8 Comment(1)
Read this article: An ESBuild Setup for TypeScript. It explicitly explains why Vite doesn't support TypeScript 5's Stage-3 decorators.Victorious
O
6

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

Oraliaoralie answered 26/7, 2023 at 19:24 Comment(2)
For tracking purposes: github.com/evanw/esbuild/issues/104Katekatee
Same issue with modern angular since it uses those tools by default now.Katekatee

© 2022 - 2024 — McMap. All rights reserved.