Lets face it code formatting is real pain, specially when working on shared projects. Fortunately we have got prettier to solve this problem. This is article is a short guide for setting up prettier in Visual Studio Code, But IDE would do.
What's Prettier?
Prettier is an opinionated code formatter, for many languages,like Javacript, CSS, JSX.. (mostly all client side tools) and also can be extended to other languages with community plugins
Time to setup
I will scaffold a quick react typescript project using vite.
npm create vite@latest
Install prettier
Install prettier as a dev dependency, this helps us to configure prettier on a per page project
npm install --save-dev --save-exact prettier
Create file name .prettierrc.json
This will act as the configuration file for prettier. It can be configured using json, YAML or javascript I will be using json
{
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"arrowParens": "avoid"
}
This would format the code by using a tab space of 2, adding semi colons at the end of all line endings, using single quotes instead of double, and omits parathesis in arrow functions whenever possible
More rules can be found Rules
now you can run prettier using
npx prettier --write .
Great!, but can still do better, instead of manually running the configuration we can setup our IDE/Text Editor to help us out.
I am giving the guide for VS Code
Install the prettier extension
Open Settings
You can quickly configure the settings by using settings.json file
Press CMD+OPTION+P or CTRL+ALT+P and type in open settings json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
}
This will use the formatting option as prettier and follow the configuration set in the configuration file created earlier and also apply formatting when you save or paste a code.
Bam !!
But what if you need to ignore certain files from formatting say the package-lock.json or the dist/build files. That where .prettierignore comes into play
Create a file called .prettierignore. This works similar to .gitignore and you can follow the same setup
Hope you guys loved it. This is the first part of setting up a good DX using Vite and React. eventually reaching https://github.com/sharath-mohan/react-dx-template this template.
If you liked this article, a star on the github repo would be awesome
Top comments (2)
amazing bro ty
Simple and easy. Thanks.