diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index 2f42909e0c6f82..15b4c32d0a2e39 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -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'; } @@ -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;