Skip to content

Latest commit

 

History

History
126 lines (84 loc) · 2.39 KB

prefer-module.md

File metadata and controls

126 lines (84 loc) · 2.39 KB

Prefer JavaScript modules (ESM) over CommonJS

This rule is part of the recommended config.

🔧💡 This rule is auto-fixable and provides suggestions.

Prefer using the JavaScript module format over the legacy CommonJS 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.

    Replacements:

    import {fileURLToPath} from 'url';
    import path from '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 '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