wessberg / DI-compiler

A Custom Transformer for Typescript that enables compile-time Dependency Injection
MIT License
80 stars 7 forks source link

Does this work with @rollup/plugin-typescript ? #13

Closed lgirma closed 3 years ago

lgirma commented 3 years ago

Asking this since the @rollup/plugin-typescript plugin supports transformers option for typescript.

I tried but getting this error:

TypeError: Cannot read property 'getTypeChecker' of undefined
lgirma commented 3 years ago

Up on further investigation, I got it to work using (in rollup config):

import typescript from '@rollup/plugin-typescript'

...

plugins: [typescript({
  transformers: {
    before: [ { type: 'program', factory: (program) => di({program}).before[0] } ],
    after: [ { type: 'program', factory: (program) => di({program}).after[0] } ]
  }
})]

This generates the correct bundle like:

container.registerSingleton(undefined, { identifier: 'HackerNewsService', implementation: HackerNewsService });

But the javascript code for all of my classes (like HackerNewsService above) are omitted. And thus running into HackerNewsService is not defined errors.

wessberg commented 3 years ago

Hi there,

The DI-Compiler must be passed a TypeScript Program since it depends on a type checker. That's why you need to pass the program on to it.

Your example doesn't work, though, as you pass the DI Custom Transformer twice, one for the before hook and one for the after hook. That's not correct usage of it. The DI custom transformer must be passed a program, and it itself returns a structure of the form {before, after}.

If you experience issues with interoperability between @rollup/plugin-typescript and Custom Transformers such as DI-Compiler, I suggest that you open an issue with a minimal repro over at the Rollup plugins monorepo. Specifically, it should be able to handle Custom Transformers that implement multiple hooks, such as DI-compiler, that does things in both the before and after hooks.

In the meantime, you can use DI-Compiler with rollup-plugin-ts which is tested and verified to be working correctly.

SitamMatt commented 2 years ago

Hi,

I've wrote a workaround helper for @rollup/plugin-typescript to easly apply this transformer. Here is the npm link

Usage:

import typescript from "@rollup/plugin-typescript";
import { di } from "@wessberg/di-compiler";
import { applyTransformer } from "rollup-typescript-custom-transformer-helper";

(...)

typescript({
  sourceMap: true,
  inlineSources: true,
  transformers: {
    ...applyTransformer((program) => di({ program })),
  },
}),