Transpile TypeScript In Memory With Node
Asked Answered
D

3

12

Is there a way to transpile TypeScript in memory with Node? I would like to be able to get the generated JavaScript in memory.

Dramshop answered 25/2, 2015 at 21:20 Comment(3)
You can load the compiler into node, which modules like gulp-typescript do. Not sure if they operate fully in-memory.Syncretize
Assuming by "in memory" you just mean "not written to a file" then yeah, you can use gulp-tsc to compile the TypeScript and then pipe it anywhere you want. I'm sure there are tons of examples of this online, but if you'd liek an example- here's one of my gulpfiles that uses gulp-tsc: github.com/bvaughn/task-runner/blob/master/gulpfile.js#L97Southwards
Transpile it to a file, read it into memory and delete the fileCorrigible
B
11

Yes. TypeScript provides a a ts.transpileModule function:

const ts = require('typescript');
const source = "let x: string  = 'hello world'";
const result = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS }});
console.log(result.outputText); // var x = 'hello world';

More

Burlie answered 25/2, 2015 at 23:42 Comment(1)
Typescript-Simple is no longer maintained.Sil
D
3

We ended up developing our own solution based on the native TypeScript transpileModule functionality.

FROM TYPESCRIPT DOCS

TranspileModule will compile source text from 'input' argument using specified compiler options. If no options are provided - it will use a set of default compiler options. Extra compiler options that will unconditionally be used by this function are:

  • isolatedModules = true
  • allowNonTsExtensions = true
  • noLib = true
  • noResolve = true

transpile() - This code will transpile TypeScript to JavaScript (typescriptServices.min.js from TypeScript is required):

export function transpile(tscode: string): TYPE.EVENT {

    interface TranspileOptions {
        compilerOptions?: any
        fileName?: string;
        reportDiagnostics?: boolean;
        moduleName?: string;
        renamedDependencies?: any;
    }

    interface TranspileOutput {
        outputText: string;
        diagnostics?: any[];
        sourceMapText?: string;
    }

    let compilerOptions: ts.CompilerOptions = {
        isolatedModules: false
    }

    let options: TranspileOptions = {
        compilerOptions: compilerOptions,
        reportDiagnostics: true
        // moduleName: modulename
    }

    let info: TYPE.EVENT;

    try {

        // Transpile the ts code to js.
        let ret: TranspileOutput = ts.transpileModule(tscode, options);

        // If diagnostics were returned.
        // NOTE: The transpiler is currently always return a message (code=5047) about 'isolatedModules', which
        // is not relavent for our use. If there is more than one row than there is in fact an error.
        if (ret.diagnostics && ret.diagnostics.length > 0) {

            let code = ret.diagnostics[0].code;

            if (code == 5047) {
                return (info = {
                    success: true,
                    returnvalue: ret.outputText,
                    caller: LibCore.getFunctionName(arguments)
                })
            } else {

                let text = ret.diagnostics[0].messageText;
                // let hint = ret.diagnostics[0].file.parseDiagnostics[0].file.nextContainer.symbol.name;

                return (info = {
                    success: false,
                    returnvalue: ret.diagnostics,
                    message: `Syntax error: ${text} Code: ${code}`,
                    caller: LibCore.getFunctionName(arguments)
                })
            }

        } else {
            return (info = {
                success: true,
                returnvalue: ret.outputText,
                caller: LibCore.getFunctionName(arguments)
            })
        }

    } catch (e) {
        return (info = {
            success: false,
            message: e.message,
            caller: LibCore.getFunctionName(arguments)
        })
    }
} 
Dramshop answered 12/2, 2016 at 17:21 Comment(2)
Cool. Do you know how to get the definitions .d.ts output from the API?Michi
Would have been nice to see the import-statements as wel.Sil
G
0

Not exactly an answer to the question, but if your main reason for wanting to try in-memory compiler is performance, what worked for me was resetting types and lib in compilerOptions.

const program: ts.Program = createProgram([entryFile], {
  types: [],
  lib: [],
});

My build speedup from 10 seconds to 100ms. I didn't need external types and libs in my project, so that was an easy fix for me.

Gerdy answered 10/3 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.