Skip to main content

no-var-requires

禁止除 import 语句之外的 require 语句.

已弃用

此规则已被弃用,以支持 @typescript-eslint/no-require-imports 规则。

¥This rule has been deprecated in favour of the @typescript-eslint/no-require-imports rule.

换句话说,禁止使用诸如 var foo = require("foo") 之类的形式。而是使用 ES6 样式导入或 import foo = require("foo") 导入。

¥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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-var-requires": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

var foo = require('foo');
const foo = require('foo');
let foo = require('foo');
Open in Playground

选项

该规则接受以下选项:

type Options = [
{
/** 允许从中获取的导入路径模式。 */
allow?: string[];
},
];

const defaultOptions: Options = [{ allow: [] }];

¥Options

allow

允许从中获取的导入路径模式。 Default: [].

字符串数组。这些字符串将使用 u 标志编译为正则表达式,并用于针对导入的路径进行测试。常见用例是允许导入 package.json。这是因为 package.json 通常位于 TS 根目录之外,因此静态导入它会导致根目录冲突,尤其是在启用 resolveJsonModule 的情况下。如果你的环境不支持 JSON 模块,你还可以使用它来允许导入任何 JSON,或者在 import 语句无法工作的其他情况下使用它。

¥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.

使用 {allow: ['/package\\.json$']}

¥With {allow: ['/package\\.json$']}:

const foo = require('../data.json');
Open in Playground

何时不使用它

¥When Not To Use It

如果你的项目经常使用较旧的 CommonJS require,那么此规则可能不适用于你。如果只有项目的子集使用 require,那么你可能考虑在特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥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.

相关

¥Related To

资源