Lucas Rudd
Lucas Rudd

Reputation: 415

How to pass in transformers to ts-node?

I'm trying to roll my own compiler for Typescript due to the fact that I need to use transformers.

We use ts-node to run some files (individual tests, etc.) and I also need the transformers to get passed in to the ts-node compiler.

Here's my code

const ts = require('typescript');
const tsNode = require('ts-node').register;
const keysTransformer = require( 'ts-transformer-keys/transformer');
const tsConfig = require( './tsconfig.json');

const compileProject = () => {
    const { options, fileNames } = ts.parseJsonConfigFileContent(
        tsConfig,
        ts.sys,
        __dirname
    );
    const program = ts.createProgram(fileNames, options);

    const transformers = {
        before: [keysTransformer(program)],
        after: []
    };

    program.emit(undefined, undefined, undefined, false, transformers);
}

const compileAndRun = (files) => {
    tsNode({ files, compilerOptions: tsConfig.compilerOptions, transformers: ["ts-transformer-keys/transformer"] });
    files.forEach(file => {
        require(file);
    });
}

module.export = main = (args) => {
    if(args.length >= 2) {
        const fileNames = args.splice(2);
        compileAndRun(fileNames);
    } else {
        compileProject();
    }
}

main(process.argv);

Passing in the transformer to the TypeScript compiler (when compiling the entire project) works just fine by doing

const transformers = {
    before: [keysTransformer(program)],
    after: []
};

However, I cannot see to find sufficient documentation on how to do the same with ts-node.

Upvotes: 2

Views: 927

Answers (1)

DDS
DDS

Reputation: 4375

The transformers option to register() is of the CustomTransformers type (not an array as you're passing):

    interface CustomTransformers {
        /** Custom transformers to evaluate before built-in .js transformations. */
        before?: (TransformerFactory<SourceFile> | CustomTransformerFactory)[];
        /** Custom transformers to evaluate after built-in .js transformations. */
        after?: (TransformerFactory<SourceFile> | CustomTransformerFactory)[];
        /** Custom transformers to evaluate after built-in .d.ts transformations. */
        afterDeclarations?: (TransformerFactory<Bundle | SourceFile> | CustomTransformerFactory)[];
    }

Upvotes: 2

Related Questions