How To Setup Prettier Formatter
Setup prettier for nextjs (or reactjs) using npm or yarn package manager
This article is meant to guide you on how to add prettier formatter to an already existing project.
Note: This article assumes that you have a nextjs project (or reactjs as the case maybe) already created and wish to add prettier formatter to your existing project.
For this tutorial, we shall be making use of a basic npx create-next-app project
. Let us get straight into it.
Step 1: Install prettier as a devDependency.
In your command line, type in the following command:
npm install --save-dev prettier
If you are using the yarn package installer, type in:
yarn add -D prettier
Step 2: Create .prettierrc.json
file
Once installation is done, the next step is to create a .prettierrc.json
file in your project root directory.
In your command line, enter:
touch .prettierrc.json
Note: You can also create a .prettierrc.json
file manually. Both methods give the desired result.
Step 3: Configuration.
Now, we configure .prettierrc.json
by adding the following code inside the file:
{
"tabWidth": 2,
"useTabs": false,
"printWidth": 80,
"semi": true,
"trailingComma": "all",
"jsxSingleQuote": false,
"singleQuote": false
}
Note: These are my preferred configurations. If you do not like it and wish to make changes suitable for your project, you can make more research on how to do so in the prettier official documentation
Step 4: Configure the scripts.
Enter into your package.json file, add this configuration to the scripts:
"scripts": {
...
"format": "prettier --check --ignore-path .gitignore .",
"format:fix": "prettier --write --ignore-path .gitignore ."
},
Note: The .gitignore file was added to the --ignore-path option to ignore the files not managed by Git.
Step 6: Run the scripts.
Type in the command terminal:
npm run format
For yarn:
yarn run format
Some files will violate the styles being enforced by the prettier formatter. Below is a pictorial example of some of the errors you might encounter:
Step 6: Fix code style (and resolve the errors)
The code style can be fixed, hence, fixing the errors thrown in the command line. We are going to execute our second script by typing in the command line the following:
npm run format:fix
If you are using yarn, enter:
yarn run format:fix
This should fix all the files and resolve the errors. Below is a picture of expected output:
Step 7: Re-run npm run fix
In the command line, type in the following:
npm run fix
For yarn:
yarn run fix
This should be the expected output:
Mission accomplished ๐๐. You have successfully set up prettier for your nextjs project.
If you found this article helpful, kindly comment, like and share this post if it helped you achieve your desired result.
I'll see you in the next one. Happy Coding!! โค๏ธ โค๏ธ
Reach out to me on my twitter