Welcome, Developer 🖖
Keen to learn how to promote a standardized code styling across your React application code? Then follow me!
Table of contents
Open Table of contents
Introduction
Regardless if you’re working only by yourself or with a team of developers, it’s important to have a standard on how to write the code.
Imagine how challenging would it be to read and maintain a codebase where each developer writes the code in a distinct way?
It affects not only the quality of your application but the performance of the team.
To promote code styling standards withing our team, or even when working by ourselves, we can use a library called Prettier.
Let’s learn more about it, developer 👍
Pre-requisites
First of all, we need a React application previously created. As our purpose is only to explore Prettier and ESLint today, the boilerplate in its original state is enough.
Run the command to create a React TypeScript app using Vite as build tool:
npm create vite@latest my-app -- --template react-ts
Just about compatibility, from Vite:
Vite requires Node.js version 18+. 20+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it.
What is Prettier?
Prettier is an opinionated code formatter, originally forked from recast.
Its almost 50k stars on GitHub and more than 32 million weekly downloads on npm, makes it one of the most popular code formatters out there (if not the most).
It’s pretty simple to setup and provides a long list of rules you can set to format your code, from how you format strings to adding semicolons to the code.
How does Prettier work?
It could not rephrase it better:
Prettier enforces a consistent code style (i.e. code formatting that won’t affect the AST) across your entire codebase because it disregards the original styling by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary.
Install
Let’s start by installing the Prettier npm package to our app:
npm install --save-dev --save-exact prettier
Setup
Next, we need to create a configuration file that Prettier uses as reference when formatting our code. This file is called .prettierrc
and will be created on the root level of our application:
node --eval "fs.writeFileSync('.prettierrc','{}\n')"
If you prefer any other format for your configuration file, check the documentation page.
By having an empty object {}
as the file content, it means Prettier will follow its standard rules (list). It could be a good idea sometimes to go with the default rules if your team takes too much discussing about what rules are applicable to the codebase. It’s up to you and your team.
If I may suggest a list of rules that works great for me personally, it is:
{
"singleQuote": true,
"semi": true,
"printWidth": 100,
"bracketSameLine": true,
"jsxSingleQuote": true,
"useTabs": true
}
It’s a personal choice, make sure to choose the rules that make most sense to you and your team 👌
Now, we must tell Prettier to ignore a few files when formatting our application code. This file is called .prettierignore
, it uses gitignore syntax, and will be created on the root level of our application:
node --eval "fs.writeFileSync('.prettierignore','')"
Open the file, and paste the following content to it:
# Ignore artifacts:
build
coverage
Don’t worry about the node_modules
folder, it’s ignored by default. It will also follow rules specified in the .gitignore
file if it exists in the same directory.
Last but not least, shall we run the following command to format our code:
npx prettier . --write
No errors? All good? Cool, our files should have been formatted according to the rules defined on the configuration file ✅
Script Commands
We don’t want to have to run that command manually, do we? Let’s add it to the package.json
file under the scripts
section:
"scripts": {
"prettier-check": "prettier . --check",
"prettier-write": "prettier . --write"
}
It goes without saying, but prettier . --check
only verify if the files are following the defined rules. It informs the list of unformatted files, if any.
Try running to ensure it works as expected:
npm run prettier-check
npm run prettier-write
Quick Tip
Install the Prettier extension to your Visual Studio Code. It makes it easy to have your file formatted as soon as you save it!
On your settings JSON file, add the properties:
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
Done, nice job 🚀
Pre-commit Hooks
So far, we’ve seen only how to manually run the code that formats our code.
Can we guarantee that every developer (including us) will remember to run it every time before committing changes? Almost impossible, isn’t it?
Prettier suggests a few options for pre-commit hooks. A Pre-commit Hook is an action that runs before a git commit. My favourite option is lint-staged.
Let’s run the command to create a pre-commit hook in the application:
npx mrm@2 lint-staged
This installs husky and lint-staged, then add a configuration to the project’s package.json that will automatically format supported files in a pre-commit hook:
{
"name": "my-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
...
"prettier-check": "prettier . --check",
"prettier-write": "prettier . --write",
"prepare": "husky install"
},
...
"lint-staged": {
"*.{js,jsx,ts,tsx,md,html,css}": "npm run prettier-write"
}
}
You can set what file extensions to apply the formatting prettier-write
command to.
Conclusion
Thank you for following along with me, developer 😎
I hope you have learned something new, or at least, refreshed your knowledge about code styling.
Take care, and see you in the next one 👋