kach / nearley

📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
https://nearley.js.org
MIT License
3.57k stars 231 forks source link

produce grammar as ECMAScript module? #585

Open franktip opened 3 years ago

franktip commented 3 years ago

Hi, is it possible to have nearleyc produce an ECMAScript module, in which the the produced grammar is the default export? This would make it easier to use the generated parsers in a server-side setting. Currently, the generated parser contains:

if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') { module.exports = grammar; } else { window.grammar = grammar; }

which does not work on platforms where the "window" variable is not defined.

Right now, I have a workaround that relies on manual editing the generated parser, which is not ideal, because I have to repeat the edit every time the grammar changes.

supposedly commented 2 years ago

Just found out by accident that Nearley actually does do this: https://github.com/kach/nearley/blob/0313b2c2d96bd93d5282def0bb46351e3455f8a0/lib/generate.js#L143-L153

You can activate it by sticking @preprocessor esmodule or @preprocessor module at the top of your .ne grammar.

If you need it to work a bit differently (for example, using named exports instead of the default export) and you don't mind a bit of dirty code, you could create your own local version of the nearleyc script and monkey-patch that generate object with your own preprocessor(s). Just make sure to replace all require('../foo/bar') with require('nearley/foo/bar') and you're set!