prettier-plugin-pegjs

raw JSON →
2.0.2 verified Sat Apr 25 auth: no javascript

A Prettier plugin for formatting PEG.js and Peggy grammar files. v2.0.2 is the latest stable, requires Node >= 16 and ships TypeScript definitions. It supports standard Prettier options plus an 'actionParser' to format action code (JavaScript/TypeScript by default, configurable). Unlike generic formatters, it deeply understands PEG syntax, preserving code within actions. Available for browser via standalone bundle.

error Error: Cannot find module 'prettier-plugin-pegjs'
cause Plugin not installed or not in node_modules
fix
Run 'npm install --save-dev prettier prettier-plugin-pegjs' or 'yarn add --dev prettier prettier-plugin-pegjs'.
error SyntaxError: Unexpected token (1:1) while parsing PEG grammar
cause The grammar file is not valid PEG.js syntax (e.g., missing header or invalid rule)
fix
Check the grammar against PEG.js specification; ensure initial rule is uppercase.
error TypeError: prettier.format is not a function
cause Using CommonJS require with ESM-only version or importing incorrectly
fix
Use dynamic import: const prettier = await import('prettier'); or migrate to ESM.
gotcha The plugin parses PEG.js (original) grammar, not Peggy (fork) — ensure your grammar file uses .pegjs extension or specify parser explicitly
fix Use .pegjs extension or set parser: 'pegjs' in Prettier config
breaking v2.0.0 dropped support for Node < 16, CommonJS via require() fails
fix Upgrade to Node 16+ and use ESM imports (import) or dynamic import()
deprecated Using default export with require('prettier-plugin-pegjs') will return undefined in older versions — always use default import
fix Migrate to import syntax or upgrade to v2 (ESM only)
gotcha actionParser option defaults to 'babel-ts' — may cause parse errors if actions contain other languages
fix Set actionParser to appropriate parser (e.g., 'babel' for JavaScript without TypeScript)
npm install prettier-plugin-pegjs
yarn add prettier-plugin-pegjs
pnpm add prettier-plugin-pegjs

Formats a PEG.js grammar string using Prettier with the plugin, demonstrating usage in a Node.js TypeScript environment.

import prettier from 'prettier';
import prettierPluginPegjs from 'prettier-plugin-pegjs';

const code = `Expression = head:Term tail:(_("+"/"-")_ Term)* { return tail.reduce(function(result, element) { if (element[1] === "+") { return result + element[3]; } if (element[1] === "-") { return result - element[3]; } }, head) }`;

const formatted = await prettier.format(code, {
  parser: 'pegjs',
  plugins: [prettierPluginPegjs],
  tabWidth: 2,
});
console.log(formatted);