Outline
Prettier
is a code formatter that helps manage code style consistently.
- Prettier: https://prettier.io/
In this blog post, I will introduce how to set up Prettier
in a TypeScript
-based React
project created using Vite
to manage code format consistently.
Blog series
This blog post is part of a series. Here is the list of Vite
series.
- [Vite] Getting started with TypeScript-based React project
- [Vite] Configure test environment in TypeScript-based React project
- [Vite] Configure Prettier in TypeScript-based React project
- [Vite] Configure Stylelint(CSS-in-JS) in TypeScript-based React project
Install Prettier
To use Prettier
in a TypeScript
-based React
project created using Vite
, you need to install Prettier
. Run the following command to install Prettier
.
npm install --save-dev prettier
# yarn add -D prettier
Configure Prettier
To use the installed Prettier
, you need to configure Prettier
. Create a .prettierrc
file and modify it as follows.
{
"semi": false,
"singleQuote": true,
"jsxSingleQuote": true,
"printWidth": 100
}
"semi": false
: Do not use the last semicolon(;
)."singleQuote": true
: Use single quotes('
) by default."jsxSingleQuote": true
: Use single quotes('
) by default in JSX syntax."printWidth": 100'
: Limit the number of characters that can be written on one line to 100.
Prettier
offers various settings depending on the team and project. You can check the available options through the following link.
- Official document: https://prettier.io/docs/en/options
Set up scripts
To use the configured Prettier
, open the package.json
file and add the following scripts.
"scripts": {
...
"format": "prettier --check --ignore-path .gitignore .",
"format:fix": "prettier --write --ignore-path .gitignore ."
},
You can set the --ignore-path
option to select the .gitignore
file to exclude files that are not managed by Git
.
Execute
Now, use the following command to check the code with the contents of Prettier
set earlier.
npm run format
# yarn format
If there are files that violate the Prettier
option you set, they will be displayed as follows.
Checking formatting...
[warn] .prettierrc.js
[warn] pages/api/hello.ts
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
Execute the following command to automatically fix the violated files.
npm run format:fix
# yarn format:fix
After all files have been fixed, run the following command to check again.
npm run format
# yarn format
If all files have been fixed, the following result will be displayed.
Checking formatting...
All matched files use Prettier code style!
Completed
Done! We’ve seen how to set up Prettier
in a TypeScript
-based React
project created using Vite
. I hope you try setting up Prettier
and writing code in a consistent format.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.