diff --git a/doc/api/modules.md b/doc/api/modules.md index 4acead178e4093..ca469d635ed272 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -132,6 +132,13 @@ variable. Since the module lookups using `node_modules` folders are all relative, and based on the real path of the files making the calls to `require()`, the packages themselves can be anywhere. +## Addenda: The .mjs extension + +It is not possible to `require()` files that have the `.mjs` extension. +Attempting to do so will throw [an error][]. The `.mjs` extension is +reserved for [ECMAScript Modules][] which cannot be loaded via `require()`. +See [ECMAScript Modules][] for more details. + ## All Together... @@ -950,6 +957,8 @@ requireUtil('./some-tool'); [`createRequire()`]: #modules_module_createrequire_filename [`module` object]: #modules_the_module_object [`path.dirname()`]: path.html#path_path_dirname_path +[ECMAScript Modules]: esm.html +[an error]: errors.html#errors_err_require_esm [exports shortcut]: #modules_exports_shortcut [module resolution]: #modules_all_together [module wrapper]: #modules_the_module_wrapper diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index ff1128e903dc2e..91b89860e7b66d 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -800,11 +800,9 @@ Module._extensions['.node'] = function(module, filename) { return process.dlopen(module, path.toNamespacedPath(filename)); }; -if (experimentalModules) { - Module._extensions['.mjs'] = function(module, filename) { - throw new ERR_REQUIRE_ESM(filename); - }; -} +Module._extensions['.mjs'] = function(module, filename) { + throw new ERR_REQUIRE_ESM(filename); +}; // Bootstrap main module. Module.runMain = function() { diff --git a/test/parallel/test-require-mjs.js b/test/parallel/test-require-mjs.js new file mode 100644 index 00000000000000..69f8527555db71 --- /dev/null +++ b/test/parallel/test-require-mjs.js @@ -0,0 +1,11 @@ +'use strict'; +require('../common'); +const assert = require('assert'); + +assert.throws( + () => require('../fixtures/es-modules/test-esm-ok.mjs'), + { + message: /Must use import to load ES Module/, + code: 'ERR_REQUIRE_ESM' + } +);