輕鬆存取編譯器 API

使用 TypeScript VFS,您可以建立一個完全由您控制的獨立 TypeScript 環境。此函式庫用於支援遊樂場,並提供 twoslash 程式碼範例的基本工具。

TypeScript VFS 有 3 個主要用途

  • 建立 TypeScript 程式作為編譯器 API 的進入點
  • 執行 TypeScript 以發出檔案,例如 *.js*.d.ts*.map
  • 使用 TypeScript 的語言服務來執行編輯器會執行的相同呼叫

您可以在 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')