如何在浏览器中使用 TypeScript 编译器?

Hel*_*rld 3 typescript typescript-compiler-api

我正在尝试在浏览器(例如 Chrome)中使用 TypeScript 编译器:

import * as ts from "typescript";

[...]

const host = ts.createCompilerHost(options);

[...]
Run Code Online (Sandbox Code Playgroud)

上面的代码失败是因为 createCompilerHost 在内部引用了未定义的 ts.sys。

如何确保 ts.sys 存在?我自己可以模仿一下吗?分配 ts.sys (ts.sys = ...) 失败,因为它是只读的。

Dav*_*ret 6

这可以通过创建您自己的实现来完成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
};
Run Code Online (Sandbox Code Playgroud)

使用我的库@ts-morph/bootstrap可能会更容易,因为它应该在浏览器中工作并为您加载所有 lib 声明文件...如果它不起作用,请在存储库的问题中告诉我。要在网络上使用它,只需指定使用内存文件系统:

import { Project, ts } from "@ts-morph/bootstrap";

const project = new Project({ useInMemoryFileSystem: true });
// use project here...
Run Code Online (Sandbox Code Playgroud)