Code formatting using Prettier and Husky

Code formatter using prettier and husky

If you are code reviewer, usually you have encountered very silly but more frustrating problem due to code diff because code indentation or code alignment or different coding formats. This article helps all the full stack developers who majorly code in Typescript, Javascript and deals with json and scss formats

To maintain the automated code formatting we take help of libraries such as prettier, husky, tslint-config-prettier and all these are dev dependencies so you can install them in your project with below command

npm install -D prettier husky tslint-config-prettier

Note : If you are using java or php projects you should install other packages such as "prettier-plugin-java" and "@prettier/plugin-php"

Most of you already know that prettier is used for formatting your code but you might be wondering what is tslint-config-prettier, this is one of the nice package that helps to co-exist tslint and prettier together, all the available configuration from prettier will be read first and rest still takes configuration from tslint, so you don't have to worry about conflicts from prettier and tslint configurations

Husky plugin will help in running commands before performing any git commands, so in our scenarios we wanted to avoid any bad code formatting before committing the code, hence we can take advantage of pre-commit hook

So after installing packages you need to add new file .prettierrc which holds all the code styling configuration as below

{
  "bracketSpacing": true,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 120,
  "arrowParens": "always"
}

If you are using already tslint configuration in your existing project you need to update extends properties as below in your tslint.json

"extends": [
  "tslint:latest",
  "tslint-config-prettier"
]

And the last step you need to update the package.json with scripts and husky configurations as show below

{
  "name": "code-formatting-using-prettier-and-husky",
  "version": "0.0.0",
  "scripts": {
    "format": "prettier --config ./.prettierrc src/**/*.{ts,json,js,md,scss,html,java,php} --write"
  },
  "private": true,
  "dependencies": {
    "tslib": "^1.10.0"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run format"
    }
  },
  "devDependencies": {
    "@prettier/plugin-php": "^0.14.0",
    "husky": "^4.2.3",
    "prettier": "^2.0.2",
    "prettier-plugin-java": "^0.7.1",
    "tslint": "~5.18.0",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "~3.7.5"
  }
}

Github Repo : https://github.com/allabouttech0803/prettier-code-format

So now you are all set , as soon as you try to commit anything in the repo automatically code will be formatted and only formatted code will be git staged always , you can see in action below