【问题标题】:How do I use TypeScript compiler in the browser?如何在浏览器中使用 TypeScript 编译器?
【发布时间】:2020-04-18 16:28:11
【问题描述】:

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

import * as ts from "typescript";

[...]

const host = ts.createCompilerHost(options);

[...]

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

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

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    这可以通过创建您自己的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
    };
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-23
      • 2016-08-03
      • 1970-01-01
      • 2022-11-14
      • 2013-10-04
      • 2020-08-14
      • 2020-01-23
      • 2016-03-09
      相关资源
      最近更新 更多