javascriptnpmwebpackbuildnearley

Attempted import error with "npm run build", works with "npm start"


I have a React app that runs fine with npm start, but fails to build with the following error when running npm run build:

`Creating an optimized production build...
Failed to compile.

Attempted import error: './parseq-lang.js' does not contain a default export (imported as 'grammar').

The import statement looks like this (you can see the full file here):

import grammar from './parseq-lang.js';

The module being imported is generated code from nearleyc. Its export portion looks like this (you can see the full file here – again this is generated code, so I'd rather not change this if I can avoid it):

(function () {

[...]

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

Does anyone know what might be happening or have any pointers to help me debug? Thanks!


Solution

  • It seems nearleyc can generate an ES6 module, see the source code here: https://github.com/kach/nearley/blob/6e24450f2b19b5b71557adf72ccd580f4e452b09/lib/generate.js#L143

    According to the section "Using Preprocessors" in https://nearley.js.org/docs/parser you need to put a line @preprocessor module or @preprocessor esmodule at the top of your grammar file.