Skip to main content

no-require-imports

Disallow invocation of require().

Prefer the newer ES6-style imports over require().

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-require-imports": "error"
}
};

Try this rule in the playground ↗

Examples

const lib1 = require('lib1');
const { lib2 } = require('lib2');
import lib3 = require('lib3');
Open in Playground

Options

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$']}:

console.log(require('../data.json').version);
Open in Playground

When Not To Use It

If your project frequently uses older CommonJS requires, then this rule might not be applicable to you. If only a subset of your project uses requires then you might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

Resources