Improve your JavaScript code with ESLint and Prettier

Improve your JavaScript code with ESLint and Prettier

Javascript gives you a lot of space for freedom compared to strictly typed languages. Freedom is power. But with great power comes great responsibility. Especially if your project team size is more than one person.

So it's always a good idea to have a standard code style. This post will describe the setup I have for most of my NodeJS projects. We will need ESLint, Prettier, Husky and lint-staged packages.

npm i -D eslint

After installation we can initialize it:

./node_modules/.bin/eslint --init

You can choose your settings from the interactive command interface. For example for the Devio API project I use the following settings in .eslintrc.js:

module.exports = {
  env: {
    browser: true,
    es6: true,
  },
  extends: [
    "airbnb-base",
  ],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly",
  },
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: "module",
  },
  rules: {
    "no-console": 1,
    "no-underscore-dangle": [
      "error",
      {
        "allow": [
          "_id"
        ]
      }
    ],
    "arrow-body-style": 1
  },
};

And yes I chose the Airbnb style for my projects. You can replace it either with Standard or Google style.

To check a particular file run:

./node_modules/.bin/eslint app.js

For general errors ESLint offers automatic fix:

./node_modules/.bin/eslint app.js --fix

If you have folders or files you want to exclude from checking ESLint supports gitignore syntax. Just place the .eslintignore file in the root directory. For example:

src/routes/*
!src/routes/index.js

Now let's add Prettier

npm i -D prettier-eslint prettier-eslint-cli

Prettier supports gitignore syntax. Create .prettierignore file in the root directory.

Let's add npm scripts to run the above commands on all files in the package.json. For excluding particular files or directories use ignore files.

"eslint": "./node_modules/.bin/eslint '**/*.{js,ts,tsx}'",
"eslint:fix": "./node_modules/.bin/eslint '**/*.{js,ts,tsx}' --fix",
"format": "prettier-eslint $PWD/'**/*.{js,ts,tsx}' --write"

And the last step is to automate running these commands before committing to the repository. Install husky and lint staged packages:

npm i -D husky lint-staged

Update package.json file:

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.(js|jsx|ts|tsx)": [
      "npm run eslint:fix",
      "npm run format",
      "git add"
    ]
  }

Test it:

git add appWithErrors.js 
git commit -m "pre-commit hook testing"

Happy fixing!