Skip to content

module: refine module type mismatch error cases

This fixes up the error message in the case when importing a CJS module that contains ES module syntax.

Specifically, hiding the cjs-module-lexer parse failure message, and also then surfacing the warning context that informs the user about the "type" and ".mjs" format indicators to be able to correct the underlying issue.

Before this change:

import { name } from './module.cjs';

where module.cjs contains export / import syntax so is not valid CommonJS, would output as per the error in https://github.com/nodejs/node/issues/35425.

With this change, we now get an error like:

(node:7249) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/guybedford/Projects/node/test/fixtures/es-modules/invalid-cjs.js:1
export var name = 5;
^^^^^^

SyntaxError: Unexpected token 'export'
Checklist
  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • commit message follows commit guidelines

Merge request reports

Loading