no-require-imports
Disallow invocation of
require()
.
Extending "plugin:@typescript-eslint/recommended"
in an ESLint configuration enables this rule.
Prefer the newer ES6-style imports over require()
.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-require-imports": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-require-imports": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
const lib1 = require('lib1');
const { lib2 } = require('lib2');
import lib3 = require('lib3');
Open in Playgroundimport * as lib1 from 'lib1';
import { lib2 } from 'lib2';
import * as lib3 from 'lib3';
Open in PlaygroundOptions
This rule accepts the following options:
type Options = [
{
/** Patterns of import paths to allow requiring from. */
allow?: string[];
/** Allows `require` statements in import declarations. */
allowAsImport?: boolean;
},
];
const defaultOptions: Options = [{ allow: [], allowAsImport: false }];
allow
Patterns of import paths to allow requiring from. Default: []
.
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
console.log(require('../data.json').version);
Open in Playgroundconsole.log(require('../package.json').version);
Open in PlaygroundallowAsImport
Allows require
statements in import declarations. Default: false
.
When set to true
, import ... = require(...)
declarations won't be reported.
This is useful if you use certain module options that require strict CommonJS interop semantics.
With {allowAsImport: true}
:
- ❌ Incorrect
- ✅ Correct
var foo = require('foo');
const foo = require('foo');
let foo = require('foo');
Open in Playgroundimport foo = require('foo');
import foo from 'foo';
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.