gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:38:38 24 4
gpt4 key购买 nike

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

import * as ts from "typescript";

[...]

const host = ts.createCompilerHost(options);

[...]

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

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

最佳答案

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

关于typescript - 如何在浏览器中使用 TypeScript 编译器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com