輕鬆訪問編譯器 API

TypeScript VFS 允許你建立一個完全由你掌控的、自包含的 TypeScript 環境。該庫用於驅動 Playground,併為 twoslash 程式碼示例提供了底層工具支援。

TypeScript VFS 主要有 3 種用途:

  • 建立一個 TypeScript 程式作為編譯器 API 的入口點
  • 執行 TypeScript 以輸出檔案,如 *.js*.d.ts*.map
  • 使用 TypeScript 的語言服務(Language Service)進行與編輯器相同的呼叫

你可以在 TypeScript VFS README 中瞭解更多資訊

透過 node_modules 設定 TypeScript

import ts from 'typescript'
import tsvfs from '@typescript/vfs'

const fsMap = tsvfs.createDefaultMapFromNodeModules({ target: ts.ScriptTarget.ES2015 })
fsMap.set('index.ts', 'console.log("Hello World")')

// ....
              

使用 TypeScript CDN 獲取你的 lib.d.ts 檔案

import ts from 'typescript'
import tsvfs from '@typescript/vfs'

const fsMap = await tsvfs.createDefaultMapFromCDN(compilerOptions, ts.version, true, ts)
fsMap.set('index.ts', 'console.log("Hello World")')

const system = tsvfs.createSystem(fsMap)
const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts)

const program = ts.createProgram({
  rootNames: [...fsMap.keys()],
  options: compilerOptions,
  host: host.compilerHost,
})

// This will update the fsMap with new files
// for the .d.ts and .js files
program.emit()

// Now I can look at the AST for the .ts file too
const index = program.getSourceFile('index.ts')