Getting started with Prettier under 1 minute

ranjanranjan
2 min read

The image is of Nanda Devi Peak, UK, IN

When a lot of people work on a project we all follow our own rules or not of how code will look ,spacing indentation ,some would use ; some might not and so on but it might lead to less readability , how it would be if all the code by everyone looks the same with same rules ?? Here comes:

Prettier is like a maid for your code house(project), it cleans and arranges it so it looks neat, same style everywhere, no fighting over tabs vs spaces with your family(team)

and a professional definition would be : Prettier is an opinionated code formatter that enforces a consistent coding style by parsing your code and re-printing it with rules for spacing, indentation, line breaks, and other stylistic elements.

How to add this to a project (**JS,TS based )

  1. Inside project root run :

     # Install Prettier with npm
     npm install -D prettier
     #OR
     # Install Prettier with yarn
     yarn add -D prettier
    
  2. Create a config file .prettierrc (root of project) and Add :

    these are some generic configs ,play around with these or add more

     {
       "semi": true,
       "singleQuote": true,
       "trailingComma": "es5",
       "tabWidth": 2,
       "printWidth": 80
     }
    

    use this for further knowledge of options you can put inside this config https://prettier.io/docs/configuration.html

  3. Add .prettierignore to skip stuff:

    You can add or remove any file you like but this is generally skipped , cause you don’t want prettier to mess up with these

     node_modules
     dist
     build
     *.env
    
  4. Optionally add script in package.json:

     "scripts": {
       "format": "prettier --write ."
     }
    
  5. Run this to auto-fix whole project:

     # for npm
     npm run format
     # OR
     #for yarn
     yarn format
    
0
Subscribe to my newsletter

Read articles from ranjan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ranjan
ranjan