Skip to content

Commit

Permalink
fixup! module: clarify require not defined error message
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Mar 21, 2021
1 parent 6889055 commit b732c67
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
19 changes: 14 additions & 5 deletions lib/internal/modules/esm/module_job.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ const {
ReflectApply,
SafeArrayIterator,
SafeSet,
StringPrototypeEndsWith,
StringPrototypeIncludes,
StringPrototypeMatch,
StringPrototypeReplace,
StringPrototypeSplit,
StringPrototypeStartsWith,
} = primordials;

const { ModuleWrap } = internalBinding('module_wrap');
Expand Down Expand Up @@ -154,11 +156,18 @@ class ModuleJob {
try {
await this.module.evaluate(timeout, breakOnSigint);
} catch (e) {
if (e.name === 'ReferenceError' &&
e.message === 'require is not defined') {
e.message += ' in ES module scope. You can use `await import` instead' +
', or use `.cjs` extension to load the file as CommonJS ' +
'module.';
if (e.name === 'ReferenceError' && (
e.message === 'require is not defined' ||
e.message === 'module is not defined'
)) {
e.message += ' in ES module scope. You can use `await import` instead';

if(StringPrototypeEndsWith(this.module.url, '.js') &&
StringPrototypeStartsWith(this.module.url, 'file://')) {
e.message +=
'. It seems you are trying to load a file using `.js` extension ' +
'inside a folder containing a `package.json`; you need to use '+ 'the `.cjs` extension to load the file as a CommonJS module';
}
}
throw e;
}
Expand Down
14 changes: 14 additions & 0 deletions test/es-module/test-esm-undefined-require.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
'use strict';
const common = require('../common');
const fixtures = require('../common/fixtures');
const assert = require('assert');

assert.rejects(
import('data:text/javascript,require;'),
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
/use .await import. instead/
).then(common.mustCall());

assert.rejects(
import('data:text/javascript,require;//.js'),
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
/^(?!It seems you are trying to load a file using `.js` extension).*$/
).then(common.mustCall());

assert.rejects(
import(fixtures.path('/es-modules/package-type-module/cjs.js')),
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
/use the .\.cjs. extension to load the file as a CommonJS module/
).then(common.mustCall());

0 comments on commit b732c67

Please sign in to comment.