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

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

The proper method for organizing a nested array object - an obstacle arises when attempting to sort the array

I have a collection of data fetched from Web API 2.2 stored in an Angular array as objects. Each object represents a Client and includes properties like name, surname, and a collection of contracts assigned to that client. Here is the interface definition ...

Enhance user information by adding necessary fields

I often encounter situations where I need to select a specific entry from a set of data in a component, whether through a select box or as part of a table. However, the way I intend to utilize this data typically requires additional fields like the "label ...

Specialized input process based on the product category of a WooCommerce item

I've been struggling to enable decimal quantities in WooCommerce but can't figure out why it's not working. The plugin code I've implemented successfully allows users to input decimals in 0.5 increments for products in the "Fabric" cat ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Using NestJS to pass request and response parameters

I have a function in my services set up like this: ` @Injectable() export class AppService { getVerifyToken(req: Request, res: Response) { try { let accessToken = process.env.ACCES_TOKEN_FB; let token = req.query["hub.verify_t ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

What is the easiest way to choose a child vertex with just one click on mxgraph?

I have nested vertices and I'm looking to directly select the child vertex with just one click. Currently, when I click on a child vertex, it first selects the parent vertex instead. It's selecting the parent vertex initially: To select the ch ...

Techniques for importing esm libraries without requiring the "type": "module" declaration in the package.json configuration file

I have successfully implemented a TypeScript Node project but now I am facing an issue while trying to integrate the VineJS library into the project. The problem arises because VineJS is exclusively an ESM (ECMAScript Module) package, and when adding it to ...

Organize Dates in React Table

I need help with sorting the Date column in my code. Currently, the sorting is being done alphabetically. Here is the JSON data and code snippet: JSON [ { "date": "Jun-2022" }, { "date": "Jul-2022" } ...

Click on the button to open the generated link in a new tab

How can I efficiently open a URL in a new tab after making an API call with the click of a button? Currently, the button triggers the API call and generates the URL. <button (click)="getUrl()">Connect</button> In TypeScript: getUrl() ...

Is it possible for Visual Studio Code to create type declarations?

One of my tricks for quickly obtaining typings involves deriving them from actual data: https://i.stack.imgur.com/EPtMm.png I typically use a snippet like this: const ParcelFeatureTypeInstance = {"displayFieldName":"NAMECO","fieldAliases":{"PIN":"PIN / ...

There is no imageURL property available for this type

Everything was running smoothly on my local project, but encountered errors upon deploying to Vercel: The properties imageURL and alt do not exist on type {} Despite attempting to define the types based on suggestions from Stack Overflow, the issues per ...

Concealing forms within an Angular 5 application

I'm currently working on displaying the terms of use on the initial screen along with two buttons. If the user clicks the accept button, they will be directed to the authentication form. However, if they click refuse, the "Refused Terms" screen will a ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

The Context API's `useContext` hook appears to be malfunctioning, persistently

My situation is as follows: export const LocationContext = createContext(null); export const LocationProvider = LocationContext.Provider; export const useLocationContext = () => useContext(LocationContext); Using the Provider: export const Search = () ...

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

Creating an object instance in Angular 2 using TypeScript

Looking for guidance on creating a new instance in TypeScript. I seem to have everything set up correctly, but encountering an issue. export class User implements IUser { public id: number; public username: string; public firstname: string; ...

When executing npm release alongside webpack, an error is triggered

Currently, I am following a tutorial provided by Microsoft. You can access it through this link: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-typescript-webpack?view=aspnetcore-3.1&tabs=visual-studio However, when attempting to run ...