Prefer using the JavaScript module format over the legacy CommonJS module format.
-
Forbids
'use strict'
directive.JavaScript modules use “Strict Mode” by default.
-
Forbids “Global Return”.
This is a CommonJS-only feature.
-
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);
-
Forbids
require(…)
.require(…)
can be replaced byimport …
orimport(…)
. -
Forbids
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