Skip to content

Commit b732c67

Browse files
committed
fixup! module: clarify require not defined error message
1 parent 6889055 commit b732c67

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

lib/internal/modules/esm/module_job.js

+14-5
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@ const {
1212
ReflectApply,
1313
SafeArrayIterator,
1414
SafeSet,
15+
StringPrototypeEndsWith,
1516
StringPrototypeIncludes,
1617
StringPrototypeMatch,
1718
StringPrototypeReplace,
1819
StringPrototypeSplit,
20+
StringPrototypeStartsWith,
1921
} = primordials;
2022

2123
const { ModuleWrap } = internalBinding('module_wrap');
@@ -154,11 +156,18 @@ class ModuleJob {
154156
try {
155157
await this.module.evaluate(timeout, breakOnSigint);
156158
} catch (e) {
157-
if (e.name === 'ReferenceError' &&
158-
e.message === 'require is not defined') {
159-
e.message += ' in ES module scope. You can use `await import` instead' +
160-
', or use `.cjs` extension to load the file as CommonJS ' +
161-
'module.';
159+
if (e.name === 'ReferenceError' && (
160+
e.message === 'require is not defined' ||
161+
e.message === 'module is not defined'
162+
)) {
163+
e.message += ' in ES module scope. You can use `await import` instead';
164+
165+
if(StringPrototypeEndsWith(this.module.url, '.js') &&
166+
StringPrototypeStartsWith(this.module.url, 'file://')) {
167+
e.message +=
168+
'. It seems you are trying to load a file using `.js` extension ' +
169+
'inside a folder containing a `package.json`; you need to use '+ 'the `.cjs` extension to load the file as a CommonJS module';
170+
}
162171
}
163172
throw e;
164173
}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,23 @@
11
'use strict';
22
const common = require('../common');
3+
const fixtures = require('../common/fixtures');
34
const assert = require('assert');
45

56
assert.rejects(
67
import('data:text/javascript,require;'),
78
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
89
/use .await import. instead/
910
).then(common.mustCall());
11+
12+
assert.rejects(
13+
import('data:text/javascript,require;//.js'),
14+
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
15+
/^(?!It seems you are trying to load a file using `.js` extension).*$/
16+
).then(common.mustCall());
17+
18+
assert.rejects(
19+
import(fixtures.path('/es-modules/package-type-module/cjs.js')),
20+
// eslint-disable-next-line node-core/no-unescaped-regexp-dot
21+
/use the .\.cjs. extension to load the file as a CommonJS module/
22+
).then(common.mustCall());
23+

0 commit comments

Comments
 (0)