What is the best way to provide transformers in ts-node?

Currently, I am in the process of creating my own compiler for Typescript because I require the usage of transformers.

Within our workflow, we utilize ts-node to execute specific files (such as individual tests), and it is essential that these transformers are incorporated into the ts-node compiler.

Below is the code snippet:

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

Integrating the transformer into the TypeScript compiler during the project compilation process works smoothly by using:

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

However, there seems to be a lack of comprehensive documentation regarding performing the same process with ts-node.

Answer №1

The register() method's transformers option must be of type CustomTransformers, not an array like you have been passing:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error involving key mismatch between TypeScript inherited interface and literal string type

There are 3 interfaces (A, B, and C) that all extend from a shared interface (Common). Additionally, there is a container type which holds arrays of these 3 interfaces (Container). The goal is to select one of the arrays and extract a common property from ...

Breaking down nested arrays in typescript

After receiving a response from the service, the data included the following: "rows": [ [ "stravi/aa", "202001", "59", "51", "2558.98", "0.5358894453719162", "1.9204668112983725", "140", "2.346630 ...

Error TS2304: Unable to locate identifier 'QRScanner'

I am currently exploring https://www.npmjs.com/package/cordova-plugin-qrscanner in order to implement a QR scanning feature in my mobile application. As part of the initial steps, I have written the following code snippet in my typescript file: function o ...

Changing the name of an Angular2 import module

Deciding to improve readability, I opted to rename the @angular module to angular2 and gain a better understanding of how imports function. Prior to making this change, the systemjs.config.js appeared like so: (function(global) { var map = { ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Obtain the function's return type without actually executing the function

Consider the following TypeScript function: export const foo = function(){ return { a: 1, b: true, c: 'bar' } }; If I were to import this function into another file: import {foo} from './foobar'; Is there a me ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

WebStorm highlights user-defined Jasmine matchers as mistakes and displays `TypeScript error TS2339: Property 'matcher' does not exist on type 'ArrayLikeMatchers '`

I am currently working on testing a hybrid Angular and Angular.js app using Karma / Jasmine. The previous code utilized custom matchers which worked flawlessly, and these same matchers are being used in the new TypeScript code. Strangely, although the Type ...

Tips for sorting through aggregated information in Foundry Functions

How can I filter on grouped data in Foundry Functions after grouping and aggregating my data? See the code snippet below for reference: @Function() public async grouping(lowerBound : Integer ): Promise<TwoDimensionalAggregation<string>> { ...

Unable to update markers on agm-map for dynamic display

In my Angular 5 application, I am utilizing Angular Google Maps (https://angular-maps.com/) along with socket.io for real-time data updates of latitude and longitude from the server. Although I am successfully pushing the updated data to an array in the co ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

Angular has its own unique way of handling regular expressions through its TypeScript

Considering the creation of an enum to store various regex patterns in my application for enhanced code reuse. For example: export enum Regex { ONE_PATTERN = /^[example]+$/g, ANOTHER_PATTERN = /^[test]{5,7}$/g } However: Encountering the TS90 ...

The attribute specified is not present on the element within the array

I'm attempting to create an array that includes an object with initialized properties and a number. Yet, I encounter this error message: The error states: 'Property 'foo' does not exist on type 'number | IObj'. The proper ...

The 'type' property is not present in the 'ChartComponent' type, however, it is necessary in the 'ApexChart' type

Encountered an error highlighted in the title: Property 'type' is missing in type 'ChartComponent' but required in type 'ApexChart'. Any attempt to resolve this issue led to another error message: Type '{ type: string; ...

Customize the form using a custom component in react-hook-form: setting a default value

I have been learning ReactJS + TypeScript for 3 months now. Recently, I have a question about using react-hook-form (v7) to edit a form. I want to integrate my custom component into the form and I managed to do it on my own! Here is a snippet of my form p ...

Steps for deactivating a button based on the list's size

I am trying to implement a feature where the user can select only one tag. Once the user has added a tag to the list, I want the button to be disabled. My approach was to disable the button if the length of the list is greater than 0, but it doesn't s ...

Guide on utilizing TypeScript declarations imported as `* as`

Currently, I am working with react-icons and attempting to import all icon definitions using the syntax import * as Icons from 'react-icons/fi'. However, I am facing a dilemma on how to create a type that must be one of the types exported from Ic ...

Issue with method assignment in extending Array class in Typescript

Currently, I am utilizing Typescript and Vue in my workflow, although the specific framework is not a major concern for me. I have been attempting to expand Array functionality in the following manner: class AudioArray extends Array<[number, number]&g ...

Using memoization for React Typescript callback passed as a prop

My component is designed to display data retrieved from a callback provided in the props. To prevent an infinite loop caused by mistakenly passing anonymous functions, I am looking for a method to enforce the usage of memoized callbacks. const DataRenderer ...