版本

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" */

console.log("Log a debug level message.");
console.warn("Log a warn level message.");
console.error("Log an error level message.");
console.log = 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-lineeslint-disable-line。您可以使用 no-restricted-syntax 规则来实现仅接收控制台调用错误的效果

{
    "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 中引入。

资源

更改语言