global-require
要求 require()
呼叫置於模組的最上層作用域
此規則在 ESLint v7.0.0 中已棄用。請使用 eslint-plugin-n
中的對應規則。
在 Node.js 中,模組依賴項是使用 require()
函式包含的,例如
var fs = require("fs");
雖然 require()
可以在程式碼中的任何位置呼叫,但某些風格指南規定它應該只在模組的最上層呼叫,以便更容易識別依賴項。例如,當依賴項深層嵌套在函式和其他語句中時,識別它們的難度會增加
function foo() {
if (condition) {
var fs = require("fs");
}
}
由於 require()
執行同步載入,因此在其他位置使用時可能會導致效能問題。
此外,ES6 模組規定 import
和 export
語句只能出現在模組主體的最上層。
規則詳細資訊
此規則要求所有 require()
的呼叫都位於模組的最上層,類似於 ES6 的 import
和 export
語句,它們也只能出現在最上層。
此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint global-require: "error"*/
// calling require() inside of a function is not allowed
function readFile(filename, callback) {
var fs = ;
fs.readFile(filename, callback);
}
// conditional requires like this are also not allowed
if (DEBUG) {
;
}
// a require() in a switch statement is also flagged
switch (x) {
case "1":
;
break;
}
// you may not require() inside an arrow function body
var getModule = (name) => ;
// you may not require() inside of a function body as well
function getModule(name) {
return ;
}
// you may not require() inside of a try/catch block
try {
;
} 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");
何時不應使用
如果您的模組必須使用來自檔案系統的資訊初始化,或者如果模組僅在極少數情況下使用並且會導致載入時產生大量開銷,那麼停用此規則可能是有意義的。如果您需要在 try
/catch
中 require()
可選的依賴項,您可以使用 // eslint-disable-line global-require
註解僅針對該依賴項停用此規則。
版本
此規則在 ESLint v1.4.0 中引入。