Jeffery Tang
Jeffery Tang

Reputation: 393

Trouble Using Decorators in Vite Typescript SWC

I created a vite typescript swc project, and I am having trouble getting decorators to work. I added this in tsconfig.app.json:

{
  "compilerOptions": {
    ...
    "useDefineForClassFields": true,
    ...
    "experimentalDecorators": true,
  }
  ...
}

But when I tried adding decorators:

...
function log(
  target,
  key: string,
  descriptor: PropertyDescriptor
): PropertyDescriptor {
  console.log(`Logging ${key} function`);
  return descriptor;
}

class Example {
  @log
  greet() {
    console.log("Hello, world!");
  }
}

function App() {
  const [count, setCount] = useState(0);

  const example = new Example();
  example.greet();
  ...

I get this on my website:

[plugin:vite:react-swc] × Unexpected token `@`. Expected identifier, string literal, numeric literal or [ for the computed key
    ╭─[/Users/projeffboy/Documents/playground/vite-react-ts-swc/src/App.tsx:16:1]
 13 │ }
 14 │ 
 15 │ class Example {
 16 │   @log
    ·   ─
 17 │   greet() {
 18 │     console.log("Hello, world!");
 19 │   }
    ╰────


Caused by:
    Syntax Error
/Users/projeffboy/Documents/playground/vite-react-ts-swc/src/App.tsx:16:1

What can I do to get decorators working on Vite? Or is it even possible?

Upvotes: 1

Views: 289

Answers (0)

Related Questions