Skip to content

Commit 1ecf9f7

Browse files
committed
lib,test: improves ERR_REQUIRE_ESM message
Fixes: nodejs#30599
1 parent 141a6e3 commit 1ecf9f7

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

lib/internal/modules/cjs/loader.js

+13-3
Original file line numberDiff line numberDiff line change
@@ -1195,29 +1195,39 @@ let warnRequireESM = true;
11951195
Module._extensions['.js'] = function(module, filename) {
11961196
if (filename.endsWith('.js')) {
11971197
const pkg = readPackageScope(filename);
1198+
// Function require shouldn't be used in ES modules.
11981199
if (pkg && pkg.data && pkg.data.type === 'module') {
1200+
const err = new ERR_REQUIRE_ESM(filename);
11991201
if (warnRequireESM) {
12001202
const parentPath = module.parent && module.parent.filename;
12011203
const basename = parentPath &&
12021204
path.basename(filename) === path.basename(parentPath) ?
12031205
filename : path.basename(filename);
1204-
process.emitWarning(
1206+
1207+
const warningMsg =
12051208
'require() of ES modules is not supported.\nrequire() of ' +
12061209
`${filename} ${parentPath ? `from ${module.parent.filename} ` : ''}` +
12071210
'is an ES module file as it is a .js file whose nearest parent ' +
12081211
'package.json contains "type": "module" which defines all .js ' +
12091212
'files in that package scope as ES modules.\nInstead rename ' +
12101213
`${basename} to end in .cjs, change the requiring code to use ` +
12111214
'import(), or remove "type": "module" from ' +
1212-
`${path.resolve(pkg.path, 'package.json')}.`,
1215+
`${path.resolve(pkg.path, 'package.json')}.\n` +
1216+
err.message;
1217+
1218+
// The error message should be (in this case) the as the warning.
1219+
// https://github.com/nodejs/node/issues/30599
1220+
err.message = warningMsg;
1221+
process.emitWarning(
1222+
warningMsg,
12131223
undefined,
12141224
undefined,
12151225
undefined,
12161226
true
12171227
);
12181228
warnRequireESM = false;
12191229
}
1220-
throw new ERR_REQUIRE_ESM(filename);
1230+
throw err;
12211231
}
12221232
}
12231233
const content = fs.readFileSync(filename, 'utf8');

test/es-module/test-cjs-esm-warn.js

+3
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,7 @@ child.on('close', common.mustCall((code, signal) => {
3737
`${pjson}.\n`));
3838
assert.ok(stderr.indexOf(
3939
'Error [ERR_REQUIRE_ESM]: Must use import to load ES Module') !== -1);
40+
41+
assert.strictEqual(
42+
stderr.match(/Must use import to load ES Module/g).length, 2);
4043
}));

0 commit comments

Comments
 (0)