diff options
author | Guy Bedford <guybedford@gmail.com> | 2019-10-09 17:21:31 -0400 |
---|---|---|
committer | Michaƫl Zasso <targos@protonmail.com> | 2019-11-10 14:50:07 +0100 |
commit | 2695f822bc7ce15029ec4180839959f8e9dd1fc3 (patch) | |
tree | 23261d44ab994f0e4f5aa62f0980bc74cfb6152a /lib/internal/modules | |
parent | 1fefd7fddc4092908b6660b8b4f6ccd6081102ec (diff) | |
download | node-new-2695f822bc7ce15029ec4180839959f8e9dd1fc3.tar.gz |
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/internal/modules')
-rw-r--r-- | lib/internal/modules/cjs/loader.js | 32 |
1 files changed, 27 insertions, 5 deletions
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 2d058b7e0d..64505220ab 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -261,7 +261,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; } @@ -960,13 +963,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'); |