nearley
nearley copied to clipboard
Can't use with ES6 import syntax with Node.js
I'm sure you've heard this by now, but your package doesn't work with import
syntax if I try to use it in Node.js.
The problem isn't actually that you use require
syntax, but that you assume that if module.exports
isn't defined then it's a browser environment and you set the object as a property on window
.
I'm about 95% sure that if you get rid of the assumption that window
exists and only attach it to window
after checking that it does actually exist, then it would actually work in Node with import
syntax because I've been able to use import
syntax with Node with several other packages that only had CommonJS-style exports
as long as my package.json
specified a type of module.
I would be happy to test this and, if it works, submit a PR so you could support import
syntax in Node.js without breaking anything else people are relying on.
I would honestly love to fix this if I can, because I plan on using Nearley in several upcoming projects (I hate writing parsers by hand) and I want to combine it with a library I've written that uses ES6 modules.
FWIW, if the outputted grammar file has a .cjs extension, you can import as usual from an ES module:
package.json
"scripts": { "compile": "nearleyc grammar.ne -o grammar.cjs" },
yarn run compile
index.js
import nearley from 'nearley' import grammar from './grammar.cjs' const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar))
Having to name your files with a .cjs extension is ugly. Still, it's a fix that works. But this would be such an easy fix that I don't understand why it isn't fixed yet. BTW, another thing you can't currently do is:
import {Parser, Grammar} from 'nearley';
and you have to change it to this to work:
import nearley from 'nearley';
{Parser, Grammar} = nearley;
Note: you can just tell nearlyc to compile to esm syntax (or even typescript :exploding_head: )