typescripttsctypescript-compiler-api

Is there a way to skip type checking for faster TypeScript compilation?


When using babel-preset-typescript, typechecking is skipped. This is almost certainly faster and less memory-intensive than using normal tsc because there's no type checking overhead, and the binding and checking steps are skipped completely (it's just parsing and stripping types).

I know that exactly the same thing is not available with the TS compiler API, since babel uses a different parser entirely (Bablyon). But is there a way to do something similar and skip binding and checking for faster compilation? It looks like ts.createProgram automatically includes type checking.


Solution

  • The function you are interested in is ts.transpileModule (Source / Documentation).

    For example:

    const compilerOptions: ts.CompilerOptions = {
        // you'll probably want to load this from a tsconfig.json
        target: ts.ScriptTarget.ES5,
        module: ts.ModuleKind.CommonJS
    };
    const result = ts.transpileModule("const t = 5;", {
        compilerOptions,
        reportDiagnostics: false
    });
    
    console.log(result.outputText); // "var t = 5;"
    

    So you'd want to iterate over all the typescript file paths, read them from the disk, transpile them, and then write them all to the file system as js files. You could do the reading and writing to the file system in parallel too (the compiler does this synchronously, so doing this asynchronously will yield a performance improvement).

    As you may have noticed though, ts.transpileModule will still create a program, but it should still be much faster than the regular process because it is emitting with the knowledge of only one file at a time. To skip creating a program, I believe the internal emitFiles function would need to be used... though that would require implementing the internal EmitResolver type to support the scenario, which I'm not sure is possible to do properly without binding (I don't know much about it, so can't say for sure).