prefer-const-require
Require assigning require(...) calls to a const variable.
Targeted pattern scopeโ
This rule targets require(...) calls that are not part of a variable
declaration.
What this rule reportsโ
This rule reports require(...) invocations used inline, such as return
expressions or nested call arguments.
Why this rule existsโ
Binding imports to a named const improves readability, simplifies debugging,
and avoids repeated module resolution expressions in the same scope. It also
makes migration toward ESM import style easier.
โ Incorrectโ
function loadPath() {
return require("node:path");
}
โ Correctโ
const path = require("node:path");
function loadPath() {
return path;
}
Behavior and migration notesโ
This rule has no options.
When adopting this rule, extract inline require(...) calls into top-level or
nearest-scope const bindings with descriptive names.
Additional examplesโ
logger.info(require("node:os").platform());
// โ reported: inline require call
const os = require("node:os");
logger.info(os.platform());
// โ
valid
ESLint flat config exampleโ
import etcMisc from "eslint-plugin-etc-misc";
export default [
{
plugins: { "etc-misc": etcMisc },
rules: {
"etc-misc/prefer-const-require": "error",
},
},
];
When not to use itโ
Disable this rule if your codebase intentionally allows inline CommonJS loading patterns (for example, lazy loading inside specific runtime branches).
Package documentationโ
Rule catalog ID: R056
Further readingโ
Adoption resourcesโ
- Start at warning level in CI, then move to error after cleanup.
- Use focused codemods/autofix batches per package or directory.