import/no-commonjs Restriction
What it does
Forbids the use of CommonJS require
calls. Also forbids module.exports
and exports.*
.
Why is this bad?
ESM modules or Typescript uses import
and export
syntax instead of CommonJS syntax. This rule enforces the use of more modern module systems to improve maintainability and consistency across the codebase.
Examples
Examples of incorrect code for this rule:
js
var mod = require("fs");
var exports = (module.exports = {});
exports.sayHello = function () {
return "Hello";
};
module.exports = "Hola";
Examples of correct code for this rule:
js
var a = b && require("c");
if (typeof window !== "undefined") {
require("somelib");
}
var fs = null;
try {
fs = require("fs");
} catch (error) {}
Allow require
If allowRequire
option is set to true
, require
calls are valid:
js
var mod = require("./mod");
but module.exports
is reported as usual.
Allow conditional require
By default, conditional requires are allowed, If the allowConditionalRequire
option is set to false
, they will be reported.
Allow primitive modules
If allowPrimitiveModules
option is set to true, the following is valid:
js
module.exports = "foo";
module.exports = function rule(context) {
return {
/* ... */
};
};
but this is still reported:
js
module.exports = { x: "y" };
exports.z = function bark() {
/* ... */
};