Skip to content

module: improve error message for cjs code in an esm module #53152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions lib/internal/modules/esm/module_job.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ class ModuleJob extends ModuleJobBase {
isCommonJSGlobalLikeNotDefinedError(e.message)) {
e.message += ' in ES module scope';

if (StringPrototypeStartsWith(e.message, 'require ')) {
const isRequireKeywordInEsm = StringPrototypeStartsWith(e.message, 'require ');
if (isRequireKeywordInEsm) {
e.message += ', you can use import instead';
}

Expand All @@ -276,10 +277,19 @@ class ModuleJob extends ModuleJobBase {
.getPackageScopeConfig(this.module.url);
if (packageConfig.type === 'module') {
e.message +=
'\nThis file is being treated as an ES module because it has a ' +
'\nThis file is an ES module because it has a ' +
`'.js' file extension and '${packageConfig.pjsonPath}' contains ` +
'"type": "module". To treat it as a CommonJS script, rename it ' +
'to use the \'.cjs\' file extension.';
'"type": "module". There are a variety of solutions: ' +
'\n1. Rename the file extension to \'.cjs\' to treat the file ' +
'as a CommonJS module. Other \'.js\' files will continue to be ' +
'treated as ES modules.\n2. In your ' +
`'${packageConfig.pjsonPath}' file, rename "type": "module" ` +
'to "type": "commonjs". All \'.js\' files will be treated ' +
'as CommonJS modules. ' +
(isRequireKeywordInEsm ?
'\n3. Change this file into an ES module by replacing ' +
'each require statement with an import statement.' :
'');
}
}
throw e;
Expand Down
Loading