babel-plugin-chevrotain-serialize
This plugin finds class declarations which inherit from chevrotain.Parser
, serializes them, and passes this serialization into their constructor super
calls, allowing your code to bypass parser grammar construction at runtime. This is especially useful if you run your code through a minifier, as you’ll no longer have to avoid mangling token names.
Installation
npm install --save-dev babel-plugin-chevrotain-serialize
or
yarn add --dev babel-plugin-chevrotain-serialize
Usage
Add the plugin to your .babelrc.
{
"plugins": ["babel-plugin-chevrotain-serialize"]
}
How it works
- It finds
Parser
imports which are imported using any of the methods shown below - It finds any class that inherits from the
Parser
class - If no classes inherit from
Parser
, no transform is done - this allows modules to import or require chevrotain
without being transformed - If a module contains a class which contains a class that inherits from
Parser
, the module is loaded using require-from-string
and each Parser
class is used to generate a serialized grammar - The serialized grammar is then added as a config property named
serializedGrammar
Import/Require methods
The plugin will find Parser
references which are imported and referenced in any of the following ways:
import { Parser } from "chevrotain";
const { Parser } = require("chevrotain");
class MyParser extends Parser {}
import * as chevrotain from "chevrotain";
import chevrotain from "chevrotain";
const chevrotain = require("chevrotain");
class MyParser extends chevrotain.Parser {}
const Parser1 = Parser;
class MyParser extends Parser1 {}
Limitations
Since any modules with Parser
class must be loaded using require-from-string
, it must be valid javascript loadable in node. This might require your babel config to contain a module plugin, such as @babel/plugin-transform-modules-commonjs
to transform unsupported syntax like:
import { Parser } from 'chevrotain';