Compiler
This is a complete guide to the TypeScript compiler returned by the typescript
library.
import ts from 'typescript'const x: number = 42
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.
function transpileCode(code: string): string { const { outputText } = ts.transpileModule(code, { compilerOptions: { module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.Preserve, esModuleInterop: true, declaration: true } }) return outputText}
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.).