Wij trekken vanaf woensdag 12 mei heel eventjes de officedeuren toe! ⛱
Woensdag zitten we op teambuilding 💪 en daarna komt er een verlengd Hemelvaart weekend. See ya next week! 👋

Code formatting & linting with Prettier & ESLint

Development

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. 

Tijs
7 min. reading time
Code formatting & linting with Prettier & ESLint

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'. 

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:

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: 

6 tips voor Easter Eggs commerce

6 tips voor Easter Eggs commerce

Gert-Jan 5 min. reading time
Closing an iframe the easy way

Closing an iframe the easy way

Ben 6 min. reading time

Subscribe to our newsletter

We have a monthly newsletter. Want to stay in touch about all developments in TT? Subscribe here to our newsletter!

© 2021 Made with ♡ at Herentals. Together we create digital experiences.