Acorn TypeScript Parser Plugin

1.4.13 · active · verified Sun Apr 19

acorn-typescript is an experimental alternative plugin for Acorn, a small, fast JavaScript parser. It extends Acorn to parse TypeScript scripts into a TypeScript AST, aiming for faster performance compared to other TypeScript parsers. The current stable version is 1.4.13, and it exhibits an active release cadence, frequently addressing bug fixes related to various TypeScript syntax features like optional class properties, generic types, arrow functions, and decorators. Key differentiators include its integration as an Acorn plugin, allowing existing Acorn users to add TypeScript parsing capabilities, and its specific focus on optimizing parsing speed. It supports standard TypeScript syntax, decorators, and JSX/TSX. It requires `acorn` version `>=8.9.0` as a peer dependency.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to extend Acorn's parser with the `acorn-typescript` plugin to parse TypeScript code, including basic syntax and ambient contexts using the `dts` option, ensuring `locations: true` is set.

import * as acorn from 'acorn';
import tsPlugin from 'acorn-typescript';

// Example 1: Basic TypeScript parsing
const code1 = `
const a: number = 1;
type MyType = string;
export {
  a,
  type MyType as RenamedType
};
class MyClass { accessor b = 'hello'; }
`;

const ast1 = acorn.Parser.extend(tsPlugin()).parse(code1, {
  sourceType: 'module',
  ecmaVersion: 'latest',
  locations: true // Required for acorn-typescript
});

console.log('Parsed AST 1 (basic):', JSON.stringify(ast1.body[0], null, 2));

// Example 2: Parsing within a TypeScript ambient context (.d.ts files)
const code2 = `
declare module 'my-module' {
  interface MyInterface {
    name: string;
    id: number;
  }
}
`;

const ast2 = acorn.Parser.extend(tsPlugin({ dts: true })).parse(code2, {
  sourceType: 'module',
  ecmaVersion: 'latest',
  locations: true // Still required
});

console.log('Parsed AST 2 (dts context):', JSON.stringify(ast2.body[0], null, 2));

view raw JSON →