unjs / jiti

Runtime TypeScript and ESM support for Node.js
MIT License
1.89k stars 62 forks source link

Typescript: Add support for class properties and emitDecoratorMetadata #57

Closed sreuss closed 1 month ago

sreuss commented 2 years ago

Hello,

switching Typescript transpilation to jiti in Nuxt 2.15.0 has caused some problems with our code base that have prevented us from upgrading:

We are using class-validator to validate data and define our classes like this:

export class SomeModel {
  @IsString()
  @IsDefined()
  public readonly someField!: string;
}

This causes an Error: TRANSFORM_ERROR: Definitely assigned fields cannot be initialized here, but only in the constructor on Nuxt startup which can be fixed by adding @babel/plugin-proposal-class-properties to the transformation. Somehow, @babel/plugin-syntax-class-properties is already included.

In addition, we are using Nest for our serverMiddleware and have some way to utilize it's dependency injection during server side rendering. Since the dependency injection relies on emitDecoratorMetadata we'd need babel-plugin-transform-typescript-metadata to be added to the transformation.

cshomo11 commented 1 year ago

I am also seeing issues trying to use json2typescript on a model in a Nuxt servermiddleware. I specifically see the error about using proposal-class-properties.

ERROR Decorating class property failed. Please ensure that proposal-class-properties is enabled and runs after the decorators transform.

pi0 commented 1 month ago

Consdiering you already imported IsString and IsDefined this syntax works:

export class SomeModel {
  @IsString()
  @IsDefined()
  public readonly someField: string;

  constructor(someField: string) {
    this.someField = someField;
  }
}

We also improved decorator meta support for v2.