Skip to content

Latest commit

 

History

History
135 lines (89 loc) · 3 KB

prefer-module.md

File metadata and controls

135 lines (89 loc) · 3 KB

Prefer JavaScript modules (ESM) over CommonJS

💼 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.

  1. Disallows 'use strict' directive.

    JavaScript modules use “Strict Mode” by default.

  2. Disallows “Global Return”.

    This is a CommonJS-only feature.

  3. Disallows the global variables __dirname and __filename.

    They are not available in JavaScript modules.

    Starting with Node.js 20.11, import.meta.dirname and import.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);
  4. Disallows require(…).

    require(…) can be replaced by import … or import(…).

  5. Disallows exports and module.exports.

    export … should be used in JavaScript modules.

.cjs files are ignored.

Fail

'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;

Pass

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};

Resources