prefer-module
March 27, 2026 Β· View on GitHub
π Prefer JavaScript modules (ESM) over CommonJS.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§π‘ 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
__dirnameand__filename.They are not available in JavaScript modules.
Starting with Node.js 20.11,
import.meta.dirnameandimport.meta.filenamehave been introduced in ES modules, providing identical functionality to__dirnameand__filenamein 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
URLdirectly, so you can just do this:const foo = new URL('foo.js', import.meta.url); -
Disallows
require(β¦).require(β¦)can be replaced byimport β¦orimport(β¦). -
Disallows
exportsandmodule.exports.export β¦should be used in JavaScript modules.
.cjs files are ignored.
Examples
// β
'use strict';
// β¦
// β
if (foo) {
return;
}
// β¦
// β
function run() {
if (foo) {
return;
}
// β¦
}
run();
// β
const file = path.join(__dirname, 'foo.js');
// β
const file = path.join(import.meta.dirname, 'foo.js');
// β
const file = path.join(path.dirname(url.fileURLToPath(import.meta.url)), 'foo.js');
// β
const content = fs.readFileSync(__filename, 'utf8');
// β
const content = fs.readFileSync(import.meta.filename, 'utf8');
// β
const {fromPairs} = require('lodash');
// β
import {fromPairs} from 'lodash-es';
// β
module.exports = foo;
// β
export default foo;
// β
exports.foo = foo;
// β
export {foo};
Resources
- Get Ready For ESM by @sindresorhus