EditorConfig logo

ESLint and EditorConfig in VSCode

To kick off 2019, I wanted to start the new year off with cleaner code, with more automation and less effort.  This post should help you and your team kick your new year off with consistently beautiful code, too!

Most importantly, read through to the end to find out how to turn on the “auto-format on save” settings for ESLint, which allows auto-fixing of many problems every time a file is saved!

Most of this post refers specifically to Visual Studio Code, but works similarly in many code editors.

Why?

ESLint is a popular JavaScript linter tool for identifying and reporting on patterns found in ECMAScript/JavaScript code.  EditorConfig helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs.

Both are useful for teams of developers to write clean code with consistent styling, and these tools can help you identify potential problems with your code while developing right within any editor via plugins, and may even be able to auto-fix some issues for you.

Here’s what you get:

  • See inline help for eslint errors right inside your IDE
  • Automatically fix problems and format files on save
  • Consistent code formatting across both developers and code editors
  • Better code hinting can help you catch accessibility (and other) issues before your code goes to production

Install VSCode plugins

This post focuses specifically on Visual Studio Code, but most of these concepts can be used similarly with other popular code editors.

  1. Install the EditorConfig plugin for VSCode
  2. Install the ESLint plugin for VSCode
  3. Reload VSCode to enable the new plugins.  Bonus: the  January 2019 (version 1.31) no longer requires a restart when installing/updates extensions!

Install NPM dependencies

You’ll need to install some NPM modules as devDependencies to get everything working in your project’s workspace.

npm i --save-dev eslint@latest eslint-plugin-react@latest

Above, the @latest tag is added to each package to ensure the latest version is installed, even if it is already declared in your package.json.

Configuration

There’s a bit of configuration necessary in order to make the magic happen, but a few commands and some copy/paste is all it takes to get both EditorConfig and ESLint working in VSCode.

EditorConfig

EditorConfig helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs. The EditorConfig project consists of a file format for defining coding styles and a collection of text editor plugins that enable editors to read the file format and adhere to defined styles. EditorConfig files are easily readable and they work nicely with version control systems.

EditorConfig.org

Couldn’t have said it better myself.  Sounds great, yeah?  Many IDEs and code editors (including VSCode) only need a simple plugin installed to get the benefits of consistent styling.

You should have already installed the EditorConfig plugin in the first part of this post.  If you don’t already have an .editorconfig file, create one with the following content:

# http://editorconfig.org
 
# Top-most EditorConfig file
root = true
 
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
 
[*.md]
# Don't trim trailing whitespace in Markdown (they are used to force line breaks)
trim_trailing_whitespace = false

The above code ensures that EditorConfig stops looking for more .editorconfig files at your project’s root folder, and not outside your project directory.  It also accommodates proper semantics for adding line breaks in Markdown files.

ESLint

Code linting is a type of static analysis that is frequently used to find problematic patterns or code that doesn’t adhere to certain style guidelines.

ESLint.org

This is what helps you and your team write consistent, high-quality code.  You agree on some rules for how code should be formatted, check that configuration into an application’s source control, install the appropriate IDE extensions, and then every developer on the project can more easily adhere to those rules in an automated fashion.

ESLint helps us write higher quality code because it performs static analysis on a codebase to find common errors, typos, potential performance gains, opportunities to remove redundancy, and other potential problems.

So let’s get started.  You should have already installed the ESLint plugin in the first part of this post.  We’re going to build upon the Airbnb style guide, and use the eslint-config-airbnb shared configuration for our base set of rules.  Then I’ll show you how to personalize your rules a bit more.

How to Configure ESLint

  1. Install eslint-config-airbnb and its peer dependencies.If you are using npm >= 5, run the following command in your terminal:
    npx install-peerdeps --dev eslint-config-airbnb

    If you’re using npm < 5, follow the official instructions on npmjs.org.

  2. If you don’t already have an .eslintrc file in your project’s root directory, create one with the following content:
    { "extends": "airbnb" }

Use Babel as your ESLint parser

If you’re writing modern ES6 and newer JavaScript, you’ll need to specify Babel as your parser so that ESLint can understand your code and analyze it.

First, install the babel-eslint  NPM module by running this in your terminal:

npm i babel-eslint@latest --save-dev

Then, specify babel-eslint as the parser in your .eslintrc file:

{
    "extends": "airbnb",
    "parser": "babel-eslint"
}

Specify custom rules

The Airbnb ESLint configuration is pretty reasonable, but many folks will want to override those rules with ones that make more sense for them and their applications.  Here are some custom rules which I prefer for React and ternary operators, just as an example:

{
    "extends": "airbnb",
    "parser": "babel-eslint",
    "rules": {
        "comma-dangle": "off",
        "indent": ["warn", 4],
        "react/jsx-indent": ["warn", 4, { "checkAttributes": true}],
        "react/react-in-jsx-scope": "off",
        "react/destructuring-assignment": "off",
        "no-nested-ternary": "warn",
        "react/prop-types": "warn",
        "react/prefer-stateless-function": "off"
    }
}

You can read the docs for more about custom ESLint rules.

Auto-fix ESLint errors when saving files

The easiest way to adhere to your ESLint rules is to set your editor to auto-fix warnings and errors when files are saved.

In Visual Studio Code, here’s how to do that …

Update your user settings file Cmd + , on Mac) so that files are formatted on save, and do not conflict with default VSCode settings:

# VS Code settings
#
# Notes:
#  - formatOnSave is disabled just for [javascript] to cause vscode to auto-format on save for all files except js, and let eslint take care of js files
"editor.formatOnSave": true,
"[javascript]": {
    // Let eslint do this formatting on save
    "editor.formatOnSave": false
},
 
 
# ESLint settings
"eslint.alwaysShowStatus": true,
"eslint.autoFixOnSave": true,
"eslint.provideLintTask": true

Store and share your configuration

Be sure to commit your new .eslintrc  and .editorconfig  files to source control so that they are shared by other team members working in your project.

Try it out!

Add some simple errors to your JavaScript code – for example, remove a few semi-colons or add some crazy whitespace.  Then save your file, and watch many or most of those problems become resolved automatically!

You can also bring up the “Problems” toolbox from VSCode’s status bar, view the identified ESLint issues, and even right-click and fix them with minimal effort.

You may notice some additional unrelated changes when making commits as your ESLint now auto-fixes style problems, but after some time this will subside because your files are now styled more consistently  😀