3

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.

1 Answer 1

6

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...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.