Eslint
规则 | Rules

global-require

在顶层模块范围( global-require )上强制 require()

在 Node.js 中,使用该require()函数包含模块依赖关系,例如:

var fs = require("fs"

尽管require()可以在代码中的任何地方调用,但某些样式指南规定应该仅在模块的顶层调用它,以便更容易地识别依赖关系。例如,当它们深深嵌套在函数和其他语句中时,很难确定依赖关系:

function foo() { if (condition) { var fs = require("fs" } }

由于require()做了同步加载,因此在其他位置使用时可能会导致性能问题。

此外,ES6 模块强制要求importexport声明只能出现在模块主体的顶层。

规则细节

此规则要求所有调用require()都位于模块的顶层,类似于 ES6 importexport语句,这也只能在顶层发生。

此规则的错误代码示例:

/*eslint global-require: "error"*/ /*eslint-env es6*/ // calling require() inside of a function is not allowed function readFile(filename, callback) { var fs = require('fs' fs.readFile(filename, callback) } // conditional requires like this are also not allowed if (DEBUG) { require('debug' } // a require() in a switch statement is also flagged switch(x) { case '1': require('1' break; } // you may not require() inside an arrow function body var getModule = (name) => require(name // you may not require() inside of a function body as well function getModule(name) { return require(name } // you may not require() inside of a try/catch block try { require(unsafeModule } catch(e) { console.log(e }

此规则的正确代码示例:

/*eslint global-require: "error"*/ // all these variations of require() are ok require('x' var y = require('y' var z; z = require('z').initialize( // requiring a module and using it in a function is ok var fs = require('fs' function readFile(filename, callback) { fs.readFile(filename, callback) } // you can use a ternary to determine which module to require var logger = DEBUG ? require('dev-logger') : require('logger' // if you want you can require() at the end of your module function doSomethingA() {} function doSomethingB() {} var x = require("x"), z = require("z"

何时不使用它

如果您有一个必须使用来自文件系统的信息进行初始化的模块,或者仅在非常罕见的情况下使用模块,并且会导致大量的加载开销,那么禁用该规则可能是有意义的。如果你需要require()一个内部的可选依赖try/ catch,您可以只使用这种依赖性禁用该规则// eslint-disable-line global-require评论。

版本

该规则在 ESLint 1.4.0 中引入。

资源