Setting Prettier on a React Typescript project (2022)

André Borba Netto Assis
3 min readFeb 19, 2021

--

Introduction

Prettier helps to maintain the code within some formatting rules like indentation, double or single quotes when using string, etc.

On this tutorial, I will show you how to setup and run over a React Typescript project.

So, let’s start!

Prerequisites

Note: You need Node version >= 10 installed. So, if you don’t have it, please go to nodejs website, download and install it on your local machine. (https://nodejs.org/en/)

Step 1: Create a React Project with Typescript

The following command will create a project inside a folder my-app.

On terminal:

npx create-react-app my-app --template typescript

Step 2: Install Prettier package

Inside the project directory, open a terminal.

On terminal, run:

npm install --save-dev --save-exact prettier

Step 3: ‘prettierrc.json’ file

Create a ‘.prettierrc.json’ file and add some prettier rules:

Example:

{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}

Step 4: ‘.prettierignore’ file

Create a ‘.prettierignore ‘ file and add the follow:

node_modules# Ignore artifacts:
build
coverage

Step 5: Running Prettier

Inside the project directory, open a terminal.

To run Prettier and format the code, just run:

npx prettier --write <targetFile>

Step 5.1: Let’s Run!

On the project that we create, let’s run prettier over the file App.tsx.

npx prettier --write src/App.tsx
Using Prettier on ‘App.tsx’ file

Cool, right?

Note: To run Prettier over all files in the project, just run the follow command:

npx prettier --write .

Conclusion

So, with these configurations you will improve your code formatting in your ReactJS with Typescript projects. Hope you enjoy! :)

VS Code: execute Prettier with auto-fix in a file when save

WARNING: if you intend to use Prettier together with some Linter (like ESLint), I would not recommend to go through this step and setup the auto-fix using just the Prettier rules when save, BUT using both Prettier and the Linter rules. Here there is an example of setting up auto-fix when saving a file using Prettier + ESLint rules.

As a plus, I will show you how to configure auto-fix on VS Code, but is an optional step, if you want to run prettier with auto-fix every time you save your code.

  • Create a ‘.vscode’ folder on the root of the project
  • Create a ‘settings.json’ file inside .vscode/ folder and insert the follow code on it:
.vscode/settings.json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
  • Install Prettier VSCode extension (so you can run it using some shortcuts, etc)

You can go to ‘Extensions’ section and install it manually

Prettier Extension for VSCode

Or launch VS Code Quick Open (Ctrl+P) AND Run the following command:

ext install esbenp.prettier-vscode

Done! Now every file saved will be formatted within the Prettier formatting rules.

References

--

--