no-var-requires
Disallow
require
statements except in import statements.
This rule has been deprecated in favour of the @typescript-eslint/no-require-imports
rule.
In other words, the use of forms such as var foo = require("foo")
are banned. Instead use ES6 style imports or import foo = require("foo")
imports.
module.exports = {
"rules": {
"@typescript-eslint/no-var-requires": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
var foo = require('foo');
const foo = require('foo');
let foo = require('foo');
Open in Playgroundimport foo = require('foo');
require('foo');
import foo from 'foo';
Open in PlaygroundOptions
This rule accepts the following options:
type Options = [
{
/** Patterns of import paths to allow requiring from. */
allow?: string[];
},
];
const defaultOptions: Options = [{ allow: [] }];
allow
A array of strings. These strings will be compiled into regular expressions with the u
flag and be used to test against the imported path. A common use case is to allow importing package.json
. This is because package.json
commonly lives outside of the TS root directory, so statically importing it would lead to root directory conflicts, especially with resolveJsonModule
enabled. You can also use it to allow importing any JSON if your environment doesn't support JSON modules, or use it for other cases where import
statements cannot work.
With {allow: ['/package\\.json$']}
:
- ❌ Incorrect
- ✅ Correct
const foo = require('../data.json');
Open in Playgroundconst foo = require('../package.json');
Open in PlaygroundWhen Not To Use It
If your project frequently uses older CommonJS require
s, then this rule might not be applicable to you.
If only a subset of your project uses require
s then you might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.