ESLint Setup and Configuration Guide

Comprehensive guide to setting up ESLint in VS Code for JavaScript projects. Learn configuration, rules, extensions, and best practices for maintaining code quality and consistency in development workflows.

Master ESLint from the ground up! This comprehensive guide covers everything from basic installation to advanced configuration setups. Learn how to enforce coding standards, extend popular style guides like Airbnb and Google, configure rules for different project types, and integrate ESLint seamlessly into your VS Code workflow for consistent, high-quality JavaScript development.


🎯 What is ESLint

ESLint is a static code analysis tool for identifying and fixing problems in JavaScript code. It helps developers:

  • Find and fix bugs before they reach production
  • Enforce coding standards across teams and projects
  • Maintain consistency in code style and formatting
  • Improve code quality through best practice enforcement
  • Customize rules based on project requirements

Key Benefits

  • 🔍 Early Error Detection: Catch syntax errors and potential bugs
  • 📐 Code Consistency: Enforce uniform coding styles
  • 🚀 Improved Productivity: Automated code quality checks
  • 🔧 Customizable Rules: Tailor linting to your project needs
  • 🤝 Team Collaboration: Shared coding standards

📋 Prerequisites

Before starting, ensure you have:

  • Node.js (version 12.22.0 or higher)
  • npm or yarn package manager
  • Visual Studio Code editor
  • Basic knowledge of JavaScript

Check your Node.js version:

1node --version
2npm --version

🛠️ Step 1: Install ESLint Extension in VS Code

1.1 Install the Extension

  1. Open Visual Studio Code
  2. Click the Extensions icon in the Activity Bar (Ctrl+Shift+X)
  3. Search for “ESLint”
  4. Install the ESLint extension by Dirk Baeumer

Direct Extension Link: ESLint - Visual Studio Marketplace

1.2 Verify Installation

After installation, you should see ESLint in your installed extensions list. The extension will automatically detect ESLint configurations in your projects.


🚀 Step 2: Project Setup and ESLint Installation

2.1 Initialize a New Project

Create a new project directory and initialize it:

1mkdir my-eslint-project
2cd my-eslint-project
3npm init -y

2.2 Install ESLint

You can install ESLint globally or locally (recommended):

Local Installation (Recommended):

1npm install eslint --save-dev

Global Installation:

1npm install -g eslint

2.3 Initialize ESLint Configuration

Run the ESLint configuration wizard:

1npx eslint --init

The wizard will ask several questions:

  1. How would you like to use ESLint?

    • ✅ To check syntax, find problems, and enforce code style
  2. What type of modules does your project use?

    • JavaScript modules (import/export)
    • CommonJS (require/exports)
    • None of these
  3. Which framework does your project use?

    • React
    • Vue.js
    • None of these
  4. Does your project use TypeScript?

    • Yes / No
  5. Where does your code run?

    • Browser
    • Node
  6. How would you like to define a style for your project?

    • Use a popular style guide
    • Answer questions about your style
  7. Which style guide do you want to follow?

    • Airbnb
    • Standard
    • Google
  8. What format do you want your config file to be in?

    • JavaScript
    • YAML
    • JSON

⚙️ Step 3: Configuration Files and Examples

3.1 Basic Configuration (.eslintrc.js)

Here’s a basic ESLint configuration file:

 1// .eslintrc.js
 2module.exports = {
 3  env: {
 4    browser: true,
 5    es2021: true,
 6    node: true
 7  },
 8  extends: ['eslint:recommended'],
 9  parserOptions: {
10    ecmaVersion: 12,
11    sourceType: 'module'
12  },
13  rules: {
14    indent: ['error', 2],
15    'linebreak-style': ['error', 'unix'],
16    quotes: ['error', 'single'],
17    semi: ['error', 'always']
18  }
19}

Airbnb Style Guide Configuration

 1// .eslintrc.js
 2module.exports = {
 3  env: {
 4    browser: true,
 5    es2021: true
 6  },
 7  extends: ['airbnb-base'],
 8  parserOptions: {
 9    ecmaVersion: 12,
10    sourceType: 'module'
11  },
12  rules: {
13    // Custom overrides for Airbnb rules
14    'no-console': 'warn',
15    'max-len': ['error', { code: 100 }],
16    'prefer-const': 'error'
17  }
18}

Install Airbnb config:

1npm install eslint-config-airbnb-base --save-dev

Google Style Guide Configuration

 1// .eslintrc.js
 2module.exports = {
 3  env: {
 4    browser: true,
 5    es2021: true
 6  },
 7  extends: ['google'],
 8  parserOptions: {
 9    ecmaVersion: 12,
10    sourceType: 'module'
11  },
12  rules: {
13    // Custom overrides for Google rules
14    'require-jsdoc': 'off',
15    'max-len': ['error', { code: 120 }]
16  }
17}

Install Google config:

1npm install eslint-config-google --save-dev

3.3 Hugo/Documentation Project Configuration

For Hugo-based documentation projects with JavaScript:

 1// .eslintrc.hugo.js
 2module.exports = {
 3  env: {
 4    browser: true,
 5    es2021: true,
 6    node: true
 7  },
 8  extends: ['eslint:recommended', 'prettier'],
 9  plugins: ['prettier'],
10  rules: {
11    // Hugo-specific rules for tutorial consistency
12    quotes: ['error', 'single'],
13    semi: ['error', 'always'],
14    'no-console': ['warn'], // Allow console for tutorial examples
15    camelcase: [
16      'error',
17      {
18        properties: 'always',
19        ignoreDestructuring: false
20      }
21    ],
22    'prefer-const': 'error',
23    'no-var': 'error',
24    'arrow-spacing': 'error',
25    'object-curly-spacing': ['error', 'always'],
26    'array-bracket-spacing': ['error', 'never'],
27
28    // Tutorial-specific rules
29    'max-len': [
30      'warn',
31      {
32        code: 80,
33        comments: 100,
34        ignoreUrls: true
35      }
36    ],
37    'no-magic-numbers': [
38      'warn',
39      {
40        ignore: [0, 1, -1, 2, 10, 100]
41      }
42    ]
43  },
44  overrides: [
45    {
46      // Special rules for Hugo template files
47      files: ['layouts/**/*.html'],
48      rules: {
49        'no-undef': 'off',
50        'no-unused-vars': 'off'
51      }
52    },
53    {
54      // Rules for tutorial JavaScript examples
55      files: ['content/**/*.md'],
56      rules: {
57        'no-console': 'off',
58        'no-unused-vars': 'warn'
59      }
60    }
61  ]
62}

📝 Step 4: Real-World Examples

4.1 Before and After ESLint

❌ Before ESLint (Poor Quality Code):

 1// Inconsistent style, potential issues
 2var fruits = ['apple', 'banana', 'orange']
 3function addFruit(fruit) {
 4  fruits.push(fruit)
 5  console.log('Added: ' + fruit)
 6}
 7function removeFruit(index) {
 8  if (index >= 0 && index < fruits.length) {
 9    var removed = fruits.splice(index, 1)
10    console.log('Removed: ' + removed[0])
11  } else {
12    console.log('Invalid index')
13  }
14}

✅ After ESLint (Clean, Consistent Code):

 1// ESLint-compliant code
 2const fruits = ['apple', 'banana', 'orange']
 3
 4function addFruit(fruit) {
 5  fruits.push(fruit)
 6  console.log(`Added: ${fruit}`)
 7}
 8
 9function removeFruit(index) {
10  if (index >= 0 && index < fruits.length) {
11    const removed = fruits.splice(index, 1)
12    console.log(`Removed: ${removed[0]}`)
13  } else {
14    console.warn(`Invalid index: ${index}`)
15  }
16}

4.2 Advanced Configuration with Multiple Extends

 1// .eslintrc.js - Complex project setup
 2module.exports = {
 3  env: {
 4    browser: true,
 5    es2021: true,
 6    node: true,
 7    jest: true // For testing
 8  },
 9  extends: [
10    'eslint:recommended',
11    'airbnb-base',
12    'plugin:security/recommended',
13    'prettier'
14  ],
15  plugins: ['security', 'prettier'],
16  parserOptions: {
17    ecmaVersion: 2021,
18    sourceType: 'module'
19  },
20  rules: {
21    // Security rules
22    'security/detect-object-injection': 'warn',
23
24    // Prettier integration
25    'prettier/prettier': 'error',
26
27    // Custom project rules
28    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
29    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
30
31    // Import rules
32    'import/prefer-default-export': 'off',
33    'import/no-extraneous-dependencies': [
34      'error',
35      {
36        devDependencies: ['**/*.test.js', '**/*.spec.js']
37      }
38    ]
39  },
40  overrides: [
41    {
42      files: ['**/*.test.js', '**/*.spec.js'],
43      env: {
44        jest: true
45      },
46      rules: {
47        'no-console': 'off'
48      }
49    }
50  ]
51}

🔧 Step 5: VS Code Integration and Configuration

5.1 VS Code Settings

Add these settings to your .vscode/settings.json:

 1{
 2  "eslint.enable": true,
 3  "eslint.validate": [
 4    "javascript",
 5    "javascriptreact",
 6    "typescript",
 7    "typescriptreact"
 8  ],
 9  "eslint.workingDirectories": ["src", "assets/js"],
10  "editor.codeActionsOnSave": {
11    "source.fixAll.eslint": true
12  },
13  "eslint.format.enable": true,
14  "eslint.lintTask.enable": true,
15  "eslint.run": "onSave"
16}

5.2 Package.json Scripts

Add useful npm scripts:

1{
2  "scripts": {
3    "lint": "eslint src/",
4    "lint:fix": "eslint src/ --fix",
5    "lint:check": "eslint src/ --max-warnings 0",
6    "lint:watch": "nodemon --exec 'npm run lint' --watch src/",
7    "precommit": "npm run lint:check"
8  }
9}

🎨 Step 6: Integration with Other Tools

6.1 ESLint + Prettier Integration

Install Prettier and ESLint-Prettier plugins:

1npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev

Update your ESLint config:

 1module.exports = {
 2  extends: [
 3    'eslint:recommended',
 4    'prettier' // Must be last
 5  ],
 6  plugins: ['prettier'],
 7  rules: {
 8    'prettier/prettier': 'error'
 9  }
10}

6.2 Git Hooks with Husky

Install Husky for pre-commit hooks:

1npm install husky lint-staged --save-dev
2npx husky install

Add to package.json:

 1{
 2  "lint-staged": {
 3    "*.js": ["eslint --fix", "git add"]
 4  },
 5  "husky": {
 6    "hooks": {
 7      "pre-commit": "lint-staged"
 8    }
 9  }
10}

🐛 Step 7: Common Issues and Troubleshooting

7.1 ESLint Not Working in VS Code

Problem: ESLint extension not highlighting errors

Solutions:

  1. Restart VS Code
  2. Check ESLint output panel: View > Output > ESLint
  3. Verify ESLint is installed: npx eslint --version
  4. Check configuration file syntax

7.2 Configuration Conflicts

Problem: Rules conflicting between different extends

Solution: Use configuration hierarchy:

1module.exports = {
2  extends: [
3    'eslint:recommended', // Base rules
4    'airbnb-base', // More specific
5    'prettier' // Must be last to override formatting
6  ]
7}

7.3 Performance Issues

Problem: ESLint running slowly

Solutions:

  1. Use .eslintignore file:
node_modules/
dist/
build/
*.min.js
  1. Limit file watching:
1{
2  "eslint.workingDirectories": ["src"]
3}

📊 Step 8: Best Practices and Tips

8.1 Configuration Best Practices

  1. Start with recommended rules: eslint:recommended
  2. Use popular style guides: Airbnb, Google, Standard
  3. Customize gradually: Add rules as needed
  4. Document custom rules: Comment why rules exist
  5. Use environment-specific configs: Development vs Production

8.2 Team Collaboration

  1. Commit configuration files: Share rules across team
  2. Use exact versions: Pin ESLint and plugin versions
  3. Document setup: README with setup instructions
  4. Regular updates: Keep dependencies current

8.3 Project Structure

my-project/
├── .eslintrc.js          # Main configuration
├── .eslintignore         # Files to ignore
├── .vscode/
│   └── settings.json     # VS Code settings
├── src/
│   ├── components/
│   └── utils/
└── package.json          # Scripts and dependencies

🎯 Conclusion

ESLint is an essential tool for maintaining code quality in JavaScript projects. By following this guide, you’ve learned:

Basic Setup: Installing and configuring ESLint ✅ Configuration Options: Using extends, rules, and overrides ✅ VS Code Integration: Seamless editor experience ✅ Real-world Examples: Practical code improvements ✅ Best Practices: Professional development workflows

Next Steps

  1. Explore plugins: ESLint has hundreds of community plugins
  2. Custom rules: Write your own rules for specific needs
  3. CI/CD integration: Add linting to your build pipeline
  4. Team training: Share knowledge with your development team

Additional Resources


FAQs