Code formatting & linting with Prettier & ESLint

Code formatting and code linting are important. Especially when working in a team. Let me explain to you why it matters and how we, at Think Tomorrow, integrated this into our daily routine. 
Geschreven door Tijs Verellen

Do you ever find yourself wanting to edit some of your teammates code? Adding enters, spaces or any other kind of formatting while you're reviewing it? These changes aren't necessary, but you still like to make the code more readable and easier to parse for your eyes. Turns out your colleagues are probably doing the exact same thing. Only for them, readable code probably looks different.

This back and forth of formatting each others code was distracting us from our core work and ultimately slowed us down. So we decided to sit down together with the team to decide on some coding and formatting standards. We wouldn’t be developers if we didn’t try to automate that! So our journey in search of standard formatting and linting services to include in our daily toolbox had begun.

Formatting vs linting

First of all, it's important to differentiate 'code formatting’ from 'code linting'. 

  • Formatting: visually formats the code in the same way so each code file looks and feels the same on every IDE. Formatting doesn't change the workings of the code. Think tabs vs spaces.
  • Linting: scans the code for possible bugs or improvements and will warn you about them.

As these are two different things, we were probably going to need at least two separate services. 

Formatting with Prettier

We chose to use Prettier to format our code. It's widely used in the industry and works very well out of the box. You can install Prettier via NPM or Yarn.

npm install --save-dev prettier

Prettier can be configured to your liking using a dedicated config file. The default config was already great, but we added a few custom rules. Eventually our config file turned out like this:

// .prettierrc.json in root of project
{
    "printWidth": 120, // 120 characters per line
    "singleQuote": true, // double quotes will be changed to single quotes wherever possible
    "trailingComma": "es5", // add commas after object properties or array items
    "tabWidth": 4 // tab width equal to 4 spaces
}

Now that Prettier is installed and configured, the only thing left is to run it to reformat our code. This can be done manually via the command line:

prettier --write 'resources/assets/**/*.{js,json,scss,css}'

Integrate Prettier with your IDE

Manually running the command is not ideal. Instead, let’s try to automate the process. In our team, we use two different IDEs: VS Code and PHPstorm. Luckily there's a Prettier extension/plugin for both of them. Using the extension/plugin makes it possible to run Prettier on file save.

This way your code will automatically format while you're working on your project. We really recommend this! The Prettier plugin/extension documentation can be found here: 

Git hooks

To top it all off, we run Prettier every single time we create a new commit to make sure everything is nicely formatted before we push it. More info about git hooks can be found here: https://prettier.io/docs/en/precommit.html

Prettier is easy to use and definitely takes away a lot of formatting time. 

Linting Javascript with ESLint

Code linting is a bit more complicated. We chose to use ESLint, which handles JavaScript code linting beautifully. ESLint will scan your code before compiling and it will check whether there are any bugs present. This will minimize bugs in your code while in production. ESLint can be installed via NPM or Yarn, just like Prettier:

npm install --save-dev eslint

It doesn't work straight out of the box, though. It's necessary to create your own set of rules first. To make life easier, it's possible to add preconfigured rule packages. We opted for the ESLint recommended config combined with the established AirBnb config. We changed a few rules to match our preferences and voilà, a fully configured ESLint, ready to run:

// .eslintrc.js
module.exports = {
    env: {
        browser: true,
        es2021: true,
        node: true,
    },
    extends: ['airbnb-base', 'eslint:recommended'],
    rules: {
        indent: ['error', 4],
        'comma-dangle': [
            'error',
            {
                arrays: 'always-multiline',
                objects: 'always-multiline',
                functions: 'never',
            },
        ],
        'max-len': ['error', 120],
        'wrap-iife': 0,
        'func-names': 0,
        'operator-linebreak': 0,
        'no-param-reassign': [2, { props: false }],
        'no-plusplus': 0,
        'no-restricted-syntax': 0,
        'no-underscore-dangle': 0,
        'no-new': process.env.NODE_ENV === 'production' ? 1 : 0,
        'no-console': process.env.NODE_ENV === 'production' ? 1 : 0,
        'no-alert': process.env.NODE_ENV === 'production' ? 1 : 0,
    },
};

Add ESLint to your build flow

We can run ESLint manually via the command line:

npx eslint resources/assets/front/js/**

Though just like with Prettier, running this manually isn’t very practical. Adding ESLint to your build will make it run every single time you build your code. This way you will never forget to use it. Errors and warnings can be dealt with faster, so they don't stack up. 

There's also an option in ESLint to fix problems on the spot. This means ESLint will change your source files when and where it sees fit. We’re not sure yet about this ESLint feature, as it really takes away learning possibilities. If it’s set up correctly at the start of a project, fixing some ESLint problems here and there doesn't slow you down much anyway. 

Setting up ESLint does take some time. Your team really needs to agree on certain rules and going over all of them is very time consuming. Using a prebuilt preset by tech industry leaders, like AirBnb, really speeds up that process.

Conclusion

This is what we discovered while working with these new tools:

  • No more discussions on file-per-file formatting. Our team discusses formatting as a general concept.
  • No more time wasted on reformatting each others code.
  • No more time wasted on formatting your own code. If you use an IDE plugin that lets you format on save, making sure your code looks pretty while writing it becomes obsolete. Just hit save, and Prettier does it for you.
  • Code all looks the same, which makes it a lot easier to read.
  • Bugs are a lot less frequent since using ESLint. Now we can see most problems from a mile away and fix them before testing.
  • ESLint makes you think about the quality of your code. You can do anything you want with Javascript, the way you want to. Though sometimes, that’s not the most effective way of doing so.

These tools made us realise once again that code be written in so many different ways. On top of that, the ways you can make something work are endless. That's the beauty of code, but also it’s biggest trap. Bringing some structure into this world of endless possibilities will bring efficiency, fasten up your process and improve the quality of your code. Prettier and ESLint will help you with that.

More info can be found in the respective documentation: