ESLint Integration with VS Code

Learn how to integrate and configure ESLint in VS Code.

Extending an ESLint configuration

Following are the steps to extend an ESLint configuration:

  • ESLint is now perfectly suited for palindromes.js, but if you try to run it against palindromes.test.js, it won’t go well:

    $ npx eslint palindromes.test.js
    
    /Users/tburnham/code/test-driven-palindromes/palindromes.test.js
      3:1  error  'describe' is not defined  no-undef
      4:3  error  'it' is not defined        no-undef
      5:5  error  'expect' is not defined    no-undef
    
    ✖ 3 problems (3 errors, 0 warnings)
    

    All of these problems share the same cause as the module kerfuffle earlier: ESLint doesn’t know that palindromes.test.js will be running in an environment (Jest) where describe, it, and expect are defined as globals.

  • You could fix the problem with another env entry, but there’s a better way. Jest has an official ESLint plugin, eslint-plugin-jest, which comes with several rules for identifying common test code mistakes. Go ahead and add it to the project:

    $ npm install --save-dev eslint-plugin-jest@22.1.2
    + eslint-plugin-jest@22.1.2
    
  • To apply the plugin, you need to make two changes to the ESLint configuration. First, register it in a plugins entry. And second, add its recommended configuration to the extends entry:

    // .eslintrc.js
    module.exports = {
      plugins: ['jest'],
      extends: ['eslint:recommended', 'plugin:jest/recommended'],
      parserOptions: {
        ecmaVersion: 6,
      },
      env: {
        node: true,
      },
    };
    
  • Now you should be able to lint palindromes.test.js without issue:

    $ npx eslint palindromes.test.js
    

However, there is a slight problem with this setup. Those Jest-specific configuration settings now apply to every JavaScript file in the project. We want one set of configuration rules for tests, and another set for everything else. The best way to accomplish that is to move the tests into their own subdirectory. There we can define a test-specific ESLint configuration that extends the more general configuration in the project root.

  • Remove the Jest entries by resetting the root ESLint configuration to its last committed state via VS Code’s “Discard Changes” command or from the Terminal:

    $ git checkout -- .eslintrc.js
    

The.eslintrc.js file has been completed for you below. Install the libraries and play around with the code. After that, try running npx eslint palindromes.test.js.

Get hands-on with 1200+ tech skills courses.