From b732c67cbe779e5e96c01b9b49f06895e6fb2f0e Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Sun, 21 Mar 2021 17:00:52 +0100 Subject: [PATCH] fixup! module: clarify require not defined error message --- lib/internal/modules/esm/module_job.js | 19 ++++++++++++++----- test/es-module/test-esm-undefined-require.js | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index ea10166fdd3536..ae4b7d59a7f231 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -12,10 +12,12 @@ const { ReflectApply, SafeArrayIterator, SafeSet, + StringPrototypeEndsWith, StringPrototypeIncludes, StringPrototypeMatch, StringPrototypeReplace, StringPrototypeSplit, + StringPrototypeStartsWith, } = primordials; const { ModuleWrap } = internalBinding('module_wrap'); @@ -154,11 +156,18 @@ class ModuleJob { try { await this.module.evaluate(timeout, breakOnSigint); } catch (e) { - if (e.name === 'ReferenceError' && - e.message === 'require is not defined') { - e.message += ' in ES module scope. You can use `await import` instead' + - ', or use `.cjs` extension to load the file as CommonJS ' + - 'module.'; + if (e.name === 'ReferenceError' && ( + e.message === 'require is not defined' || + e.message === 'module is not defined' + )) { + e.message += ' in ES module scope. You can use `await import` instead'; + + if(StringPrototypeEndsWith(this.module.url, '.js') && + StringPrototypeStartsWith(this.module.url, 'file://')) { + e.message += + '. It seems you are trying to load a file using `.js` extension ' + + 'inside a folder containing a `package.json`; you need to use '+ 'the `.cjs` extension to load the file as a CommonJS module'; + } } throw e; } diff --git a/test/es-module/test-esm-undefined-require.js b/test/es-module/test-esm-undefined-require.js index bf5c1d07d71d75..8be47a7b80a2a3 100644 --- a/test/es-module/test-esm-undefined-require.js +++ b/test/es-module/test-esm-undefined-require.js @@ -1,5 +1,6 @@ 'use strict'; const common = require('../common'); +const fixtures = require('../common/fixtures'); const assert = require('assert'); assert.rejects( @@ -7,3 +8,16 @@ assert.rejects( // eslint-disable-next-line node-core/no-unescaped-regexp-dot /use .await import. instead/ ).then(common.mustCall()); + +assert.rejects( + import('data:text/javascript,require;//.js'), + // eslint-disable-next-line node-core/no-unescaped-regexp-dot + /^(?!It seems you are trying to load a file using `.js` extension).*$/ +).then(common.mustCall()); + +assert.rejects( + import(fixtures.path('/es-modules/package-type-module/cjs.js')), + // eslint-disable-next-line node-core/no-unescaped-regexp-dot + /use the .\.cjs. extension to load the file as a CommonJS module/ +).then(common.mustCall()); +