Code formatting using Prettier and Husky



If you are a code reviewer, usually you have encountered a very silly but more frustrating problem due to code diff because of 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.

Packages need to be installed for code formatting

To maintain the automated code formatting we take the 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 the 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.

Why we need tslint-config-prettier ?

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 the rest still takes configuration from tslint, so you don't have to worry about conflicts from prettier and tslint configurations.

What is husky?

The husky plugin will help in running commands before performing any git commands, so in our scenarios, we wanted to avoid any lousy code formatting before committing the code, hence we can take benefit of the pre-commit hook.

So after installing packages you need to add a 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 shown 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"
  }
}

Git Repo

Github Repohttps://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.

0
0