Skip to content

Latest commit

 

History

History
45 lines (29 loc) · 3.04 KB

no-console-2-allow-some-console-methods.md

File metadata and controls

45 lines (29 loc) · 3.04 KB

no-console - 2 - Allow some console methods

This is an continuation of a post that introduced the basics of the no-console ESLint rule. Part 1 explains the advantages of the no-console ESLint rule.

In some cases, there may be a legitimate need for code to use console methods. One example is logging certain debug information in the development environment. In this case, there are a few options:

  1. Disable the no-console rule for specific lines or the entire file with // eslint-disable-next-line no-console.

    • This is usually not considered a best practice and can clutter the code.
  2. Tell ESLint to ignore certain files and folders.

    • It's also not a good idea because that disables all ESLint's protections for the matching files/folders.
  3. Modify the rule to allow certain console methods that will be used sparingly and with intent.

    allow has an array of strings which are allowed methods of the console object (Source: ESLint Docs)

    // in .eslintrc.js
    module.exports = {
      //...
      rules: {
        // ...
    
        //🙅‍♂️ Disallows ALL console methods
        "no-console": "warn",
    
        //👍 This allows console.debug, console.warn, and console.error
        "no-console": ["warn", { allow: ["debug", "warn", "error"] }],
      },
    };
Before After
all console methods disallowed image only console.log disallowed image

The console different methods in code snippet above result in different output styles:

image

🚨 Unfortunately, console.debug outputs don't appear in the Chrome console by default. Find out why and how to fix that in this article.

image