Skip to content

Commit

Permalink
module: throw on require('./path.mjs');
Browse files Browse the repository at this point in the history
This is an extremely important part of the ESM implementation
that should have been unflagged as a breaking change in v12.0.0
to allow us to unflag ESM in Node.js 12.x before LTS. Assuming we
can get consensus on this behavior I would argue that this Semver-Major
behavior change could be viewed as a Semver-Patch fix in v12.0.1

Thoughts?
  • Loading branch information
MylesBorins committed May 2, 2019
1 parent e5c8be2 commit 7e62a6f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
9 changes: 9 additions & 0 deletions doc/api/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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...

<!-- type=misc -->
Expand Down Expand Up @@ -928,6 +935,8 @@ requireUtil('./some-tool');
[`__filename`]: #modules_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
Expand Down
8 changes: 3 additions & 5 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-require-mjs.js
Original file line number Diff line number Diff line change
@@ -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'
}
);

0 comments on commit 7e62a6f

Please sign in to comment.