no-console
禁止使用 console
💡 hasSuggestions
此規則回報的部分問題可透過編輯器的建議手動修正
在設計於瀏覽器中執行的 JavaScript 中,避免使用 console
的方法被認為是最佳實務。這類訊息被認為是用於除錯目的,因此不適合發佈到客戶端。一般來說,使用 console
的呼叫應在推送到生產環境前移除。
console.log("Made it here.");
console.error("That shouldn't have happened.");
規則細節
此規則禁止呼叫或賦值給 console
物件的方法。
此規則的錯誤程式碼範例
在 Playground 中開啟
/* eslint no-console: "error" */
("Log a debug level message.");
("Log a warn level message.");
("Log an error level message.");
= foo();
此規則的正確程式碼範例
在 Playground 中開啟
/* eslint no-console: "error" */
// custom console
Console.log("Hello world!");
選項
此規則有一個物件選項用於例外情況
"allow"
具有字串陣列,這些字串是console
物件允許的方法
此規則額外的正確程式碼範例,使用範例 { "allow": ["warn", "error"] }
選項
在 Playground 中開啟
/* eslint no-console: ["error", { allow: ["warn", "error"] }] */
console.warn("Log a warn level message.");
console.error("Log an error level message.");
何時不該使用
然而,如果您正在使用 Node.js,console
用於向使用者輸出資訊,因此不完全用於除錯目的。如果您正在為 Node.js 開發,那麼您很可能不希望啟用此規則。
您可能不使用此規則的另一種情況是,如果您想要強制執行 console
呼叫,而不是 console
覆寫。例如
/* eslint no-console: ["error", { allow: ["warn"] }] */
console.error = function (message) {
throw new Error(message);
};
在上述範例中使用 no-console
規則,ESLint 將會回報錯誤。對於上述範例,您可以停用此規則
// eslint-disable-next-line no-console
console.error = function (message) {
throw new Error(message);
};
// or
console.error = function (message) { // eslint-disable-line no-console
throw new Error(message);
};
然而,您可能不希望手動新增 eslint-disable-next-line
或 eslint-disable-line
。您可以使用 no-restricted-syntax
規則來達到僅接收 console 呼叫錯誤的效果
{
"rules": {
"no-console": "off",
"no-restricted-syntax": [
"error",
{
"selector": "CallExpression[callee.object.name='console'][callee.property.name!=/^(log|warn|error|info|trace)$/]",
"message": "Unexpected property on console object was called"
}
]
}
}
相關規則
版本
此規則在 ESLint v0.0.2 中引入。