Search code examples
typescripttypescript-compiler-api

How do I use TypeScript compiler in the browser?


I'm trying to use the TypeScript compiler in the browser (e.g. Chrome):

import * as ts from "typescript";

[...]

const host = ts.createCompilerHost(options);

[...]

The above code fails because createCompilerHost references ts.sys internally, which is undefined.

How do I ensure ts.sys exists? Can I emulate it myself? assigning ts.sys (ts.sys = ...) fails because it is readonly.


Solution

  • This can be done by creating your own implementation of ts.CompilerHost:

    const compilerHost: ts.CompilerHost = {
        getSourceFile: (fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void) => {
            // you will need to implement a way to get source files here
        },
        getDefaultLibFileName: (defaultLibOptions: ts.CompilerOptions) => "/" + ts.getDefaultLibFileName(defaultLibOptions),
        writeFile: () => {}, // do nothing
        getCurrentDirectory: () => "/",
        getDirectories: (path: string) => [],
        fileExists: (fileName: string) => { /* implement this */ },
        readFile: (fileName: string) => { /* implement this */ },
        getCanonicalFileName: (fileName: string) => fileName,
        useCaseSensitiveFileNames: () => true,
        getNewLine: () => "\n",
        getEnvironmentVariable: () => "" // do nothing
    };
    

    It might be easier to use my library @ts-morph/bootstrap as that should work in the browser and load all the lib declaration files for you... if it doesn't work then let me know in an issue on the repo. To use it on the web, just specify to use an in memory file system:

    import { Project, ts } from "@ts-morph/bootstrap";
    
    const project = new Project({ useInMemoryFileSystem: true });
    // use project here...