summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorGuy Bedford <guybedford@gmail.com>2019-10-09 17:21:31 -0400
committerGuy Bedford <guybedford@gmail.com>2019-10-11 17:37:46 -0400
commitaca1c283bd8c6778b477286b8516f7c38dc9cefb (patch)
tree8b63435cde4623163602b9872d1d1acd9e62e071 /lib
parent7812a615ab3cf992e1f4c5b63a2e5cddcf1fedf6 (diff)
downloadandroid-node-v8-aca1c283bd8c6778b477286b8516f7c38dc9cefb.tar.gz
android-node-v8-aca1c283bd8c6778b477286b8516f7c38dc9cefb.tar.bz2
android-node-v8-aca1c283bd8c6778b477286b8516f7c38dc9cefb.zip
module: warn on require of .js inside type: module
PR-URL: https://github.com/nodejs/node/pull/29909 Reviewed-By: Jan Krems <jan.krems@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Diffstat (limited to 'lib')
-rw-r--r--lib/internal/modules/cjs/loader.js32
1 files changed, 27 insertions, 5 deletions
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
index 3580614481..d7e240fbea 100644
--- a/lib/internal/modules/cjs/loader.js
+++ b/lib/internal/modules/cjs/loader.js
@@ -259,7 +259,10 @@ function readPackageScope(checkPath) {
if (checkPath.endsWith(path.sep + 'node_modules'))
return false;
const pjson = readPackage(checkPath);
- if (pjson) return pjson;
+ if (pjson) return {
+ path: checkPath,
+ data: pjson
+ };
}
return false;
}
@@ -959,13 +962,32 @@ Module.prototype._compile = function(content, filename) {
return result;
};
-
// Native extension for .js
+let warnRequireESM = true;
Module._extensions['.js'] = function(module, filename) {
- if (experimentalModules && filename.endsWith('.js')) {
+ if (filename.endsWith('.js')) {
const pkg = readPackageScope(filename);
- if (pkg && pkg.type === 'module') {
- throw new ERR_REQUIRE_ESM(filename);
+ if (pkg && pkg.data && pkg.data.type === 'module') {
+ if (warnRequireESM) {
+ const parentPath = module.parent && module.parent.filename;
+ const basename = parentPath &&
+ path.basename(filename) === path.basename(parentPath) ?
+ filename : path.basename(filename);
+ process.emitWarning(
+ 'require() of ES modules is not supported.\nrequire() of ' +
+ `${filename} ${parentPath ? `from ${module.parent.filename} ` : ''}` +
+ 'is an ES module file as it is a .js file whose nearest parent ' +
+ 'package.json contains "type": "module" which defines all .js ' +
+ 'files in that package scope as ES modules.\nInstead rename ' +
+ `${basename} to end in .cjs, change the requiring code to use ` +
+ 'import(), or remove "type": "module" from ' +
+ `${path.resolve(pkg.path, 'package.json')}.`
+ );
+ warnRequireESM = false;
+ }
+ if (experimentalModules) {
+ throw new ERR_REQUIRE_ESM(filename);
+ }
}
}
const content = fs.readFileSync(filename, 'utf8');