Skip to main content

Easy access to the compiler API

TypeScript VFS lets you create a self-contained TypeScript environment entirely under your control. This library is used to power the Playground, and provides the underlying tooling for twoslash code samples.

There are 3 main uses for TypeScript VFS:

  • Creating a TypeScript Program as an entry-point to the compiler API
  • Running TypeScript to emit files like *.js, *.d.ts or *.map
  • Using TypeScript's language service to make the same calls an editor would make

You can learn more in the TypeScript VFS README

Setup with TypeScript from node_modules

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")')

// ....
              

Use the TypeScript CDN to get your lib.d.ts files

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')