no-restricted-modules
禁止透過 require
載入指定的模組
此規則在 ESLint v7.0.0 中已被棄用。請使用 eslint-plugin-n
中對應的規則。
Node.js 中的模組是一個簡單或複雜的功能,組織在一個 JavaScript 檔案中,可以在整個 Node.js 應用程式中重複使用。關鍵字 require
在 Node.js/CommonJS 中用於將模組導入應用程式。這樣,您可以進行動態載入,其中載入的模組名稱不是預先定義的/靜態的,或者僅在「真正需要」時才條件性地載入模組。
為什麼要限制模組?
如果您想限制開發人員可以使用的可用方法,禁止使用特定的 Node.js 模組可能會很有用。例如,如果您想禁止檔案系統存取,您可以封鎖 fs
模組的使用。
規則詳情
此規則允許您指定您不想在應用程式中使用的模組。
選項
此規則接受一個或多個字串作為選項:受限制模組的名稱。
"no-restricted-modules": ["error", "foo-module", "bar-module"]
它也可以接受一個包含 paths
和 gitignore 樣式 patterns
字串清單的物件。
"no-restricted-modules": ["error", { "paths": ["foo-module", "bar-module"] }]
"no-restricted-modules": ["error", {
"paths": ["foo-module", "bar-module"],
"patterns": ["foo-module/private/*", "bar-module/*","!baz-module/good"]
}]
您也可以為您想要限制的任何路徑指定自訂訊息,如下所示
"no-restricted-modules": ["error", {
"name": "foo-module",
"message": "Please use bar-module instead."
}
]
或者像這樣
"no-restricted-modules": ["error",{
"paths":[{
"name": "foo-module",
"message": "Please use bar-module instead."
}]
}]
自訂訊息將附加到預設錯誤訊息中。請注意,您可能無法為受限制的模式指定自訂錯誤訊息,因為特定模組可能符合多個模式。
要限制使用所有 Node.js 核心模組 (透過 https://github.com/nodejs/node/tree/master/lib)
{
"no-restricted-modules": ["error",
"assert","buffer","child_process","cluster","crypto","dgram","dns","domain","events","freelist","fs","http","https","module","net","os","path","punycode","querystring","readline","repl","smalloc","stream","string_decoder","sys","timers","tls","tracing","tty","url","util","vm","zlib"
]
}
範例
此規則的不正確程式碼範例,其中範例受限制的模組為 "fs"
、"cluster"
、"lodash"
在線上試驗場中開啟
/*eslint no-restricted-modules: ["error", "fs", "cluster"]*/
var fs = ;
var cluster = ;
在線上試驗場中開啟
/*eslint no-restricted-modules: ["error", {"paths": ["cluster"] }]*/
var cluster = ;
在線上試驗場中開啟
/*eslint no-restricted-modules: ["error", { "patterns": ["lodash/*"] }]*/
var pick = ;
此規則的正確程式碼範例,其中範例受限制的模組為 "fs"
、"cluster"
、"lodash"
在線上試驗場中開啟
/*eslint no-restricted-modules: ["error", "fs", "cluster"]*/
var crypto = require('crypto');
在線上試驗場中開啟
/*eslint no-restricted-modules: ["error", {
"paths": ["fs", "cluster"],
"patterns": ["lodash/*", "!lodash/pick"]
}]*/
var crypto = require('crypto');
var pick = require('lodash/pick');
版本
此規則是在 ESLint v0.6.0 中引入的。