在 JavaScript,雖然console被設計為在瀏覽器中執行的,但避免使用console的方法被認為是一種最佳實踐。這樣的消息被認為是用于調試的,因此不適合輸出到客戶端。通常,在發布到產品之前應該剔除console的調用。
// 不提倡使用
console.log("Made it here.");
console.error("That shouldn't have happened.");
/*eslint no-console: "error"*/
console.log("Log a debug level message.");
console.warn("Log a warn level message.");
console.error("Log an error level message.");
正確 代碼示例:
/*eslint no-console: "error"*/
// custom console
Console.log("Hello world!");
如果你在使用 Node.js,然后,console
主要用來向用戶輸出信息,所以不是嚴格用于調試目的。如果你正在做 Node.js 開發,那么你很可能不想啟用此規則。
選項{ "allow": ["warn", "error"] }的 正確 代碼示例:
// 在js文件里面加入下面一行代碼,就可以調用console.warn和console.error
/*eslint no-console: ["error", { allow: ["warn", "error"] }] */
console.warn("Log a warn level message.");
console.error("Log an error level message.");