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