diff options
author | Giorgos Ntemiris <ntemirisgiorgos3@gmail.com> | 2019-07-27 20:23:25 +0200 |
---|---|---|
committer | Rich Trott <rtrott@gmail.com> | 2019-08-13 11:19:48 -0700 |
commit | 427e5348a267b7c88879b47f8d942fc3e84b30e9 (patch) | |
tree | 1f0cd8630b7754cb15a343854bdb9ae0fd0cc444 /lib | |
parent | a49b20d3245dd2a4d890e28582f3c013c07c3136 (diff) | |
download | android-node-v8-427e5348a267b7c88879b47f8d942fc3e84b30e9.tar.gz android-node-v8-427e5348a267b7c88879b47f8d942fc3e84b30e9.tar.bz2 android-node-v8-427e5348a267b7c88879b47f8d942fc3e84b30e9.zip |
module: add warning when import,export is detected in CJS context
This will allow users to know how to change their project to support
ES modules.
PR-URL: https://github.com/nodejs/node/pull/28950
Reviewed-By: Bradley Farias <bradley.meck@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/internal/modules/cjs/loader.js | 66 |
1 files changed, 48 insertions, 18 deletions
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 5d5767e0cf..3d440202c2 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -85,6 +85,29 @@ const relativeResolveCache = Object.create(null); let requireDepth = 0; let statCache = null; + +function enrichCJSError(err) { + const stack = err.stack.split('\n'); + + const lineWithErr = stack[1]; + + /* + The regular expression below targets the most common import statement + usage. However, some cases are not matching, cases like import statement + after a comment block and/or after a variable definition. + */ + if (err.message.startsWith('Unexpected token export') || + (/^\s*import(?=[ {'"*])\s*(?![ (])/).test(lineWithErr)) { + process.emitWarning( + 'To load an ES module, set "type": "module" in the package.json or use ' + + 'the .mjs extension.', + undefined, + undefined, + undefined, + true); + } +} + function stat(filename) { filename = path.toNamespacedPath(filename); if (statCache !== null) { @@ -828,24 +851,31 @@ function wrapSafe(filename, content) { } : undefined, }); } - - const compiled = compileFunction( - content, - filename, - 0, - 0, - undefined, - false, - undefined, - [], - [ - 'exports', - 'require', - 'module', - '__filename', - '__dirname', - ] - ); + let compiled; + try { + compiled = compileFunction( + content, + filename, + 0, + 0, + undefined, + false, + undefined, + [], + [ + 'exports', + 'require', + 'module', + '__filename', + '__dirname', + ] + ); + } catch (err) { + if (experimentalModules) { + enrichCJSError(err); + } + throw err; + } if (experimentalModules) { const { callbackMap } = internalBinding('module_wrap'); |