Babel Plugin: Syntax TypeScript
@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
-
Error: Parsing error: Unexpected token
cause Babel is attempting to parse TypeScript syntax without the necessary plugin enabled.fixEnsure `@babel/plugin-syntax-typescript` (or `@babel/preset-typescript`) is correctly added to your Babel plugins/presets configuration, and that Babel is processing `.ts` or `.tsx` files. Also, specify `filename` if using Node API. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use CommonJS `require()` in an ESM context, typically when importing Babel 7's core or plugins in an ESM project.fixFor Babel 7+, use ES module `import` syntax (`import { transformSync } from '@babel/core';`) when working in an ES module environment. Babel 8 is ESM-first.
Warnings
- breaking Babel 8 drops support for TypeScript's legacy `module <identifier>` syntax. This specifically impacts users relying on internal (namespace-like) modules or older ambient module declarations in TypeScript.
- breaking In Babel 8, the `transform` function in `@babel/core` will become purely asynchronous. The synchronous behavior in Babel 7 for calls without a callback will be removed.
- gotcha This plugin (`@babel/plugin-syntax-typescript`) *only* enables parsing of TypeScript syntax. It does *not* remove type annotations or transpile TypeScript to JavaScript. For full transformation, you must also use `@babel/plugin-transform-typescript` or, more commonly, `@babel/preset-typescript`.
- gotcha Babel does not perform type-checking. Even with `@babel/preset-typescript`, your TypeScript code will be transpiled to JavaScript without validating its types. This can lead to runtime errors that a full TypeScript compiler (`tsc`) would catch.
Install
-
npm install babel-plugin-syntax-typescript -
yarn add babel-plugin-syntax-typescript -
pnpm add babel-plugin-syntax-typescript
Imports
- Config via .babelrc
{ "plugins": ["syntax-typescript"] }{ "plugins": ["@babel/plugin-syntax-typescript"] } - Node API (transformSync)
require('babel-core').transform("code", { plugins: ["syntax-typescript"] });import { transformSync } from '@babel/core'; const code = `const x: string = 'hello';`; const output = transformSync(code, { plugins: ['@babel/plugin-syntax-typescript'], filename: 'input.ts' // Important for Babel to infer syntax }); console.log(output.code); - Combining with preset-typescript
plugins: ['@babel/plugin-syntax-typescript', '@babel/plugin-transform-typescript']
import { transformSync } from '@babel/core'; const code = `interface MyInterface { name: string; } const x: MyInterface = { name: 'world' };`; const output = transformSync(code, { presets: ['@babel/preset-typescript'], filename: 'input.ts' }); console.log(output.code); // Should output 'const x = { name: 'world' };'
Quickstart
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);
}