@typescript-eslint/no-require-imports
Disallow require() in favor of import
Also called typescript-eslint/no-require-imports, typescript/no-require-imports
In a TypeScript file, a call to require() returns any, so you lose checking and completion for everything you take from the module. The call can also sit anywhere in the code, which hides what the file depends on. An import is typed and sits at the top level.
import name = require("..") is reported too. A require that the file declares itself isn't.
This rule is off by default. Bun runs require() and import in the same file, and some code has no other way to write it, like plugins: [require("tailwindcss-animate")] in a Tailwind config or <Image source={require("./logo.png")} /> in React Native.
Configure#
Off by default. To turn it on:
[lint.rules]
"@typescript-eslint/no-require-imports" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/no-require-imports" = ["error", {
allow = [], # list of strings
allowAsImport = false,
}]Examples#
const path = require("node:path")A require() style import is forbidden.;
import fs = require("node:fs")A require() style import is forbidden.;
console.log(path.join("a", "b"), fs.existsSync("a"));import path from "node:path";
import * as fs from "node:fs";
console.log(path.join("a", "b"), fs.existsSync("a"));import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const addon = require("./addon.node");Options#
| Option | Default | What it does |
|---|---|---|
allow | [] | Regular expressions. A require() of a path that matches one of them is allowed. |
allowAsImport | false | Allow import name = require(".."). |
Not reported with allow: ["/package\\.json$"]:
{ "allow": ["/package\\.json$"] }No problemsconst { version } = require("../package.json");With allowAsImport, the first line is allowed and the second is still reported:
{ "allowAsImport": true }1 problemimport fs = require("node:fs");
const path = require("node:path")A require() style import is forbidden.;