Babel Plugin: Syntax TypeScript

7.0.0-alpha.19 · active · verified Sun Apr 19

@babel/plugin-syntax-typescript is a core Babel plugin that enables Babel's parser to understand and parse TypeScript syntax without performing any transformations or type-checking. This plugin is essential for any Babel setup that needs to process TypeScript files, acting as the foundational layer for interpreting TypeScript-specific language features like type annotations, interfaces, and enums. It is typically used in conjunction with `@babel/plugin-transform-typescript` (or `@babel/preset-typescript`) for removing type annotations and transforming TypeScript code into standard JavaScript. The package is part of the actively developed Babel ecosystem, with `v7.29.2` being a recent stable release and `v8.0.0-rc.3` representing the upcoming major version, which includes significant breaking changes. Babel's release cadence is frequent, providing regular updates and security patches across both major versions. Key differentiators include its role in a highly configurable JavaScript transpilation pipeline and its ability to integrate with existing build tools, offering a performance advantage over `tsc` for pure transpilation by skipping type-checking.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `@babel/plugin-syntax-typescript` for parsing TypeScript code and contrasts it with `@babel/preset-typescript` for full transformation (type stripping).

import { transformSync } from '@babel/core';

// Example TypeScript code with type annotations
const tsCode = `
interface User {
  id: number;
  name: string;
}

function greetUser(user: User): string {
  return `Hello, ${user.name}! Your ID is ${user.id}.`;
}

const currentUser: User = { id: 123, name: 'Alice' };
console.log(greetUser(currentUser));
`;

// The plugin-syntax-typescript *only* allows parsing, not transformation (type removal)
// To transform (remove types), we usually use @babel/preset-typescript
try {
  const parsedOnly = transformSync(tsCode, {
    // Using the syntax plugin directly requires 'isTSX' or 'dts' options for context
    // For simple TS parsing, it works, but doesn't remove types.
    plugins: [['@babel/plugin-syntax-typescript', { isTSX: false, dts: false }]],
    filename: 'input.ts' // Crucial for Babel to correctly interpret .ts files
  });
  console.log('--- Parsed Only (types still present in AST, but not transformed) ---');
  console.log(parsedOnly.code);

  // To actually remove types and transpile to plain JavaScript
  const transformedCode = transformSync(tsCode, {
    presets: ['@babel/preset-typescript'], // This preset includes both syntax and transform plugins
    filename: 'input.ts'
  });
  console.log('\n--- Transformed (types removed) ---');
  console.log(transformedCode.code);
} catch (error) {
  console.error('Babel transformation failed:', error);
}

view raw JSON →