Skip to content

Latest commit

 

History

History
119 lines (79 loc) · 1.9 KB

prefer-module.md

File metadata and controls

119 lines (79 loc) · 1.9 KB

Prefer JavaScript modules (ESM) over CommonJS

Prefer using the JavaScript module format over the legacy CommonJS module format.

  1. Forbids 'use strict' directive.

    JavaScript modules use “Strict Mode” by default.

  2. Forbids “Global Return”.

    This is a CommonJS-only feature.

  3. Forbids 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. Forbids require(…).

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

  5. Forbids 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