global-require
此规则在 ESLint v7.0.0 中已弃用。请使用 eslint-plugin-node
中的相应规则。
在 Node.js 中,模块依赖是使用 require()
函数包含的,例如:
var fs = require("fs");
虽然 require()
可以在代码中的任何位置调用,但一些样式指南规定它只能在模块的顶层调用,以便更容易识别依赖关系。例如,当它们深深嵌套在函数和其他语句中时,可以说更难识别依赖关系:
function foo() {
if (condition) {
var fs = require("fs");
}
}
由于 require()
进行同步加载,因此在其他位置使用时可能会导致性能问题。
此外,ES6 模块要求 import
和 export
语句只能出现在模块主体的顶层。
规则详情
1MHLRWTC2hPSpuwbkGCTRPfFzRjeFgoKk6cw20KAGJWtSb3ELjkUaW6ctzcqso/i6k0Y7ZBsHBPleu2qQqkTpD9Mbc+z7SaFXplVmnHPrul6+vvqJp+aaHiOuwD6ft83N5q7bSYGNnR/rerqtw5ewa81LM7f2Hir1zGd8z+OplIPI+xcJf8nYaqWYFlaqfnka6dzdG+uM9lVi+WjNyiW2Jp3DC655Y2GEOkOqPJdnJmh9DqNY3VvvJdU2uB0pDzK
Wk+Mu7oFIccqpNSe5orR05ZG/BDV40hHIKzF0SoJnVcuS8r6evQjx3oyoFn9+fZT
/*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);
}
UubGaThNGVSAZCEeqgdAAx/QE1uwW/De5ytjPBnKCKqeOsDZpJS0MvQSJQtY0WPI
/*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");
何时不使用
B5/GBJvQ3fUIHShrZfedm7lI9S96HcGD4LwyOcNcY8NJ1DGhM5AfSddOggIlq5F55ONWMWEoOwRc767YI1HGkpQydW2qEehNH16rj7UPLyC8NcNZzGUCLQXeY3Y5RiW4J/ZSF4jwfNgAhEJ1Dgf4v1bhbbxFYwTt5Wth6bpA3LK6K9en9tbXTteum6k2HAgUWX5IeQeVDp/oa76t7IIYRsdi8f9azMg/0Reia2guKXVBOkL80oNfr7H9/25T/+9CRghjFOZRoV2uzWM4fhrJbZoD6zNp/QAS6HPJ9yZc1hs3e+Fd0F6tB/6B/LUs7NpHRl91tzUQkFTvfJYHgbwvr8aP8sMvmZC5DlsiryiUlSOqVmVNUv2x09jBK5WBbLhN4ABWzSf5T4Lh2x7P2OP0854vR43y6dk94c7gEVEXZUMCKA6du31epGF88WVDxgNdzMXAU2k0ZfsLxAsodc32m5QhqxZt954bY13q6nBb/UxWsadSxZ9PZxGt5HrbujVLHK7gEOOVe2mRkQ1t8ANqXI6HEDRA6nQNM3yDgxiE6d+s/v0/zF6N7C3tPYpZ5VGadc+tXrRMa7g6sBY6fErr4A==