首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

no-console

"extends": "eslint:recommended"配置文件中的属性启用此规则。

在设计为在浏览器中执行的JavaScript中,避免使用方法被认为是最佳做法console。这些消息被认为是用于调试目的,因此不适合发送给客户端。一般来说,使用电话console在被推送到生产之前应该被剥离。

代码语言:javascript
复制
console.log("Made it here.");
console.error("That shouldn't have happened.");

规则细节

此规则禁止调用console对象的方法。

此规则的错误代码示例:

代码语言:javascript
复制
/*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.");

此规则的正确代码示例:

代码语言:javascript
复制
/*eslint no-console: "error"*/

// custom console
Console.log("Hello world!");

选项

该规则有一个例外的对象选项:

  • "allow"有一个允许console对象的方法的字符串数组

带有示例选项的此规则的其他正确代码示例{ "allow": ["warn", "error"] }

代码语言:javascript
复制
/*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,那么您很可能不希望启用此规则。

另一种可能不使用此规则的情况是,如果您想强制进行控制台调用而不是控制台覆盖。例如:

代码语言:javascript
复制
/*eslint no-console: ["error", { allow: ["warn"] }] */
console.error = function (message) {
  throw new Error(message);
};

根据no-console上述示例中的规则,ESLint将报告一个错误。对于上述示例,您可以禁用该规则:

代码语言:javascript
复制
// 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规则达到只接收控制台调用错误的效果:

代码语言:javascript
复制
{
    "rules": {
        "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 0.0.2中引入的。

资源

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com