Compiler

This tutorial is designed to showcase advanced usage of the TypeScript compiler.

You can use the TypeScript compiler programmatically by importing the typescript library.

ESM
import ts from 'typescript'

Transpiling

The TypeScript Compiler API's transpileModule function allows you to programmatically transpile TypeScript code into JavaScript without generating full type-checking or emitting declaration files. It's useful for cases where you want to transpile TypeScript code into JavaScript in a custom build process, or if you don't want to set up a full TypeScript project or invoke the TypeScript compiler in the traditional way.

The transpileCode function converts a single TypeScript file into JavaScript, handling only the transformation of TypeScript features like type annotations, interfaces, and other TypeScript-specific syntax, which JavaScript doesn't understand. The example above also preserves any JSX for further processing later on.

Important notes about transpiling

  • No Type Checking: Unlike the normal tsc (TypeScript compiler) command, which also checks types, transpileModule doesn't perform any type checking. It only converts the TypeScript code into JavaScript. So, if there are type errors in your code, they won't be flagged by transpileModule.
  • No Declaration Files: It doesn't generate .d.ts declaration files. It only generates the JavaScript output.
  • Configurable Output: You can specify compiler options like module, target, jsx, etc., to customize how the TypeScript code is transpiled. This provides flexibility for different JavaScript environments (e.g., ES6, CommonJS, etc.).
Loading TypeScript...

Was this page helpful?