Level up the quality of your code base with ESLint

Khrystyna Skvarok
6 min readMay 7, 2018

When we talk about linters, we usually mention big teams working on the same code base and linters as a tool to keep this codebase tidy, consistent and maintainable. Linters solve this problem by providing you with set of rules everyone in a team should follow, but more important, linters help you to follow the best practices and help to prevent potential problems. That’s why I see a point to use linter even when you are the sole maintainer of a project. It is easy to set up and will bring only positive changes to your project. I hope you’re excited! Here are the steps we’ll be covering:

  • Adding ESLint to your project;
  • Configuring ESLint to follow the best practices (Airbnb style guide in our case);
  • Autofixing errors with ESLint;
  • Running ESLint as a pre-commit hook.

If you want to jump right away to setting up ESLint, you may skip the next chapter. If you do have one extra minute, I would love to take you on a small journey through the history of JS linters.

The history of JS linters started in 2002 with JSLint project created by Douglas Crockford as a simple website, where you could check your code for potential errors:

JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.

Then it was forked into JSHint, less opinionated, more flexible linter, which was represented not only as an online tool, but also as an npm module, that could be run from the command line. It was a huge step forward. It was 2010.

2013 brought another powerful linter — ESLint. It is the de-facto standard code analysis tool for modern JS projects. It’s extensible and can be fully customized for your needs. It has support for ES6 features, plugins available to support for React, VueJS, Angular, JSX, Flow and much more. If you are missing something, why not to write your own plugin?

ESLint has powerful CLI tool with lots of amazing options like autofixing, which we will check later. In addition to that, ESLint CLI provide great initialization tool, which will guide your through installation and build ESLint configuration file based on your preferences or existed code style. Not sure how to configure your linter? Then you might be interested in ESLint configuration like eslint-config-airbnb from Airbnb team. Other well-known base configurations are Standard, Google, Facebook, and other style guides. You will be following the best practices, but still have an option to override separate rules according to your preferences. It’s a perfect start, so let me walk you through it.

We will need to install several npm packages. All of them are well documented, so I won’t go through the configuration of each of them but guide you through the main steps. ESLint requires Node.js. I assume you have Node and npm installed already.

Install ESLint

We begin with the installation of ESLint:

npm install eslint --save-dev

Setup a configuration file (based on Airbnb style guide)

Configuration file usually locates in the root of your project and has name .eslintrс. You create it by running the command:

eslint --init

ESlint will give you three options: answer questions about your style, so you can adapt ESLint to your preferences; use a popular style guide, like Google, Airbnb or Standard; inspect your project and build a configuration based on your existing code style. Let’s select the second option and choose Airbnb style guide and JSON as config format. As a result you will get .eslintrc file, which should look like this (in minimal configuration):

{
"extends": "airbnb-base"
}

If you look into your package.json you will see a couple of new packages installed as dev dependencies. Among them, you will find eslint-config-airbnb plugin. ESLint initialization took care of installing this plugin and its dependencies for you. But if you already have ESLint configured and still want to switch to Airbnb style guide, you can always do that by following installation steps at eslint-config-airbnb readme page.

Running ESLint

That’s it, you have set up ESLint! Now you can run it on any file by command:

./node_modules/.bin/eslint yourfile.js

or if you have npm >5.2 installed, npx should already be available:

npx eslint yourfile.js

Let’s make it more comfortable to use and create an npm script which will run ESLint on all JS files in our project. In your package.json add next line:

"scripts": {
"eslint": "eslint ."
},

Now run the script:

npm run eslint

Possible outcome:

/eslint-example/test.js
1:1 error Unexpected var, use let or const instead no-var
1:5 error 'a' is assigned a value but never used no-unused-vars
✖ 2 problems (2 errors, 0 warnings)
1 error, 0 warnings potentially fixable with the `--fix` option.

That’s it, you are ready to level up your codebase. Now let’s add some cool features!

ESLint auto fix

You can tell ESLint to auto-fix errors by using --fix flag:

This option instructs ESLint to try to fix as many issues as possible. The fixes are made to the actual files themselves and only the remaining unfixed issues are output.

Let’s update our npm script again:

"scripts": {
"eslint": "eslint . --fix"
},

Now run ESLint again. You may notice that some errors from your previous ESLint output have gone. This option doesn’t guarantee that all errors and warnings will be fixed, but it does a great job overall. It’s popular now to configure your IDE to run autofix on file save. It is very handy and saves a lot of time. To be honest, I prefer to see errors before they are magically gone. I think it’s a nice way to improve your coding technique. You can see if your IDE has integration with ESLint here.

Running ESLint as pre-commit hook

Let’s take this small adventure to another level! Having ESLint running on your local machine while development is awesome and I hope you already see lots of advantages of doing that. But how about running it each time you or your teammate want to commit something? You can prevent pushing bad-formatted code into a codebase. To implement this, we will need lint-staged and husky These two tools will run our linter against staged git files and

don’t let 💩 slip into your code base!

Let’s install them:

npm install --save-dev lint-staged husky

Then we need to add a new script into our package.json:

"scripts": {
"eslint": "eslint . --cache --fix",
"precommit": "lint-staged"
},
"lint-staged": {
"*.js": ["eslint --cache --fix", "git add"]
},

Now ESLint will run every time you do git commit. Flag--fix will try to fix as many errors as possible, but if some errors are still present, you will get output like this:

husky > npm run -s precommit (node v9.3.0)❯ Running tasks for *.js
✖ npm run eslint
git add
✖ "npm run eslint" found some errors. Please fix them and try committing again.
/eslint-example/test.js
3:10 error 'foo' is defined but never used no-unused-vars
7:1 error Expected an assignment or function call and instead saw an expression no-unused-expressions
7:1 error 'bar' is not defined no-undef
/test2.js
11:3 error Parsing error: Unexpected token test
✖ 4 problems (4 errors, 0 warnings)

That’s it! Now you have a powerful tool up and running and I hope you will enjoy it. Described here is the basic setup, you can do much more. But it’s already a great start and I believe will only make you want to go further. ESLint handles code formatting for you, but I prefer to use Prettier for this purpose and keep ESLint as a guide to best practices and detection of potential problems.

In my next article, I would like to talk about another cool tool for keeping quality of your codebase in a good shape — Prettier, which will take care of formatting issues. Stay tuned!

Thank you for staying with me until these words ❤ I like to chat, so looking forward to hearing from you. If you have any feedback, questions, please let me know here or find me on Twitter. Happy coding!

--

--

Khrystyna Skvarok

Product manager, Software engineer, Human being 👩‍💻🤓 Amsterdam — Ukraine 🌾 Do good, be kind, think open-minded 🌱 Read books 🌸 Help others 🌿