💼 This rule is enabled in the ✅ recommended
config.
🔧💡 This rule is automatically fixable by the --fix
CLI option and manually fixable by editor suggestions.
Prefer using the JavaScript module format over the legacy CommonJS module format. Together with other changes, this helps the ecosystem migrate to a single, native module format.
-
Disallows
'use strict'
directive.JavaScript modules use “Strict Mode” by default.
-
Disallows “Global Return”.
This is a CommonJS-only feature.
-
Disallows the global variables
__dirname
and__filename
.They are not available in JavaScript modules.
Starting with Node.js 20.11,
import.meta.dirname
andimport.meta.filename
have been introduced in ES modules, providing identical functionality to__dirname
and__filename
in CommonJS (CJS).For most cases in Node.js 20.11 and later:
const __dirname = import.meta.dirname; const __filename = import.meta.filename;
Replacements for older versions:
import {fileURLToPath} from 'node:url'; import path from 'node:path'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(fileURLToPath(import.meta.url));
However, in most cases, this is better:
import {fileURLToPath} from 'node:url'; const foo = fileURLToPath(new URL('foo.js', import.meta.url));
And many Node.js APIs accept
URL
directly, so you can just do this:const foo = new URL('foo.js', import.meta.url);
-
Disallows
require(…)
.require(…)
can be replaced byimport …
orimport(…)
. -
Disallows
exports
andmodule.exports
.export …
should be used in JavaScript modules.
.cjs
files are ignored.
'use strict';
// …
if (foo) {
return;
}
// …
const file = path.join(__dirname, 'foo.js');
const content = fs.readFileSync(__filename, 'utf8');
const {fromPairs} = require('lodash');
module.exports = foo;
exports.foo = foo;
function run() {
if (foo) {
return;
}
// …
}
run();
const file = fileURLToPath(new URL('foo.js', import.meta.url));
import {fromPairs} from 'lodash-es';
export default foo;
export {foo};
- Get Ready For ESM by @sindresorhus