pegjs-loader
raw JSON → 0.5.8 verified Sat Apr 25 auth: no javascript
A webpack loader that compiles PEG.js grammar files into JavaScript parser modules. Current version 0.5.8 is stable with weekly npm downloads around 1,000. Requires peer dependencies PEG.js ^0.10.0 and webpack >=1. Supports options like cache, optimize, trace, allowedStartRules, and dependencies. Differentiated from alternatives like jison-loader by its tight integration with PEG.js and support for multiple parser options via query parameters.
Common errors
error Error: Cannot find module 'pegjs' ↓
cause pegjs not installed in node_modules
fix
npm install --save-dev pegjs
error Module build failed: Error: Couldn't find preset 'es2015' relative to directory ↓
cause Webpack config requires babel-loader for .js files, but pegjs-loader doesn't use babel
fix
Ensure pegjs-loader is not processed by babel; exclude node_modules or pegjs-loader from babel-loader rule
error TypeError: Cannot read property 'cacheable' of undefined ↓
cause Bug in pegjs-loader v0.2.0
fix
Upgrade pegjs-loader to v0.2.2 or later
error Error: path must be a string ↓
cause Passing non-string options as query parameters
fix
Ensure all loader options are strings (e.g., 'true' instead of true)
Warnings
breaking PEG.js updated to 0.10.0, requiring changes in grammar syntax ↓
fix Update grammars to be compatible with PEG.js 0.10.0. Refer to PEG.js changelog.
deprecated webpack 1 loaders syntax is deprecated; webpack 2+ uses 'rules' instead of 'loaders' ↓
fix Use module.rules: [{ test: /\.pegjs$/, use: 'pegjs-loader' }] in webpack 2+.
gotcha Options must be passed as query parameters; they cannot be set in a separate options object ↓
fix Append options as query string: 'pegjs-loader?cache=true'.
breaking PEG.js 0.9.0 breaking changes (e.g., no more global PEG object) ↓
fix Ensure grammar files are compatible with PEG.js 0.9.0+
Install
npm install pegjs-loader yarn add pegjs-loader pnpm add pegjs-loader Imports
- pegjs-loader wrong
import pegjs from 'pegjs-loader'correctmodule.exports = { module: { loaders: [{ test: /\.pegjs$/, loader: 'pegjs-loader' }] } } - parser wrong
const parser = require('pegjs-loader!./parser.pegjs');correctconst parser = require('./parser.pegjs'); - parser (with options) wrong
const parser = require('./parser.pegjs?cache=true');correctconst parser = require('pegjs-loader?cache=true!./parser.pegjs');
Quickstart
// webpack.config.js
module.exports = {
entry: './src/index.js',
output: { filename: 'bundle.js' },
module: {
loaders: [
{
test: /\.pegjs$/,
loader: 'pegjs-loader?cache=true&optimize=size'
}
]
}
};
// src/index.js
const parser = require('./grammar.pegjs');
const result = parser.parse('input string');
console.log(result);