no-new-require

不允许 new 接线员调用 require

Important

This rule was deprecated in ESLint v7.0.0. Please use the corresponding rule in eslint-plugin-n.

Learn more

require 函数用于包含存在于单独文件中的模块,例如:

¥The require function is used to include modules that exist in separate files, such as:

var appHeader = require('app-header');

一些模块返回一个构造函数,这可能会导致如下代码:

¥Some modules return a constructor which can potentially lead to code such as:

var appHeader = new require('app-header');

不幸的是,这很容易引起混淆,因为代码作者可能打算这样写:

¥Unfortunately, this introduces a high potential for confusion since the code author likely meant to write:

var appHeader = new (require('app-header'));

出于这个原因,通常最好禁止这种特定的表达方式。

¥For this reason, it is usually best to disallow this particular expression.

规则详情

¥Rule Details

此规则旨在消除对 new require 表达式的使用。

¥This rule aims to eliminate use of the new require expression.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-new-require: "error"*/

var appHeader = new require('app-header');

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-new-require: "error"*/

var AppHeader = require('app-header');
var appHeader = new AppHeader();

何时不使用

¥When Not To Use It

如果你正在使用 require 的自定义实现,并且你的代码将永远不会在需要标准 require(CommonJS、Node.js、AMD)的项目中使用,你可以安全地关闭此规则。

¥If you are using a custom implementation of require and your code will never be used in projects where a standard require (CommonJS, Node.js, AMD) is expected, you can safely turn this rule off.

版本

此规则是在 ESLint v0.6.0 中引入。

资源