[Next.js] Prettier

2024-05-15 hit count image

Let's see how to configure Prettier in Next.js.

Outline

In this blog post, I will introduce how to configure Prettier in the Next.js project based on TypeScript. Prettier is a code formatting tool to manage the same code style.

You can see the full source code of this blog post on the following link.

Blog list

This blog post is a series. If you want to check other blog posts of the series, see the links below.

Create Next.js project based on TypeScript

To see how to apply Prettier to the Next.js projecct, execute the following command to create a Next.js project with TypeScript,

npx create-next-app --typescript my-app

Install Prettier

Execute the following command to install Prettier.

npm install --save-dev prettier

Configure Prettier

Next, we need to configure the Prettier to use it. Create the .prettierrc.js file and modify it like the below.

module.exports = {
  semi: false,
  singleQuote: true,
  trailingComma: 'all',
};
  • semi: false: Next.js basically doesn’t use the last semicolon(;).
  • singleQuote: true: Next.js basicllay uses the single quote(').
  • trailingComma: “all”: To make small changes, if the comma can be added, add the comma to the last.

Configure scripts

To use the Prettier that we’ve set, open the package.json file and modify it like the below.

"scripts": {
  ...
  "format": "prettier --check --ignore-path .gitignore .",
  "format:fix": "prettier --write --ignore-path .gitignore ."
},

We add the .gitignore file to the --ignore-path option to ignore the files not managed by Git.

Execute

Now, execute the command below to check the code style with Prettier.

npm run format

If there is any file violated by the Prettier rules, you can see the error message like the below.

Checking formatting...
[warn] .prettierrc.js
[warn] pages/api/hello.ts
[warn] Code style issues found in the above file(s). Forgot to run Prettier?

You can fix the code style automatically by executing the command below.

npm run format:fix

After all files are fixed, execute the following command again.

npm run format

If all files are fixed well, you can see the following message.

Checking formatting...
All matched files use Prettier code style!

Completed

Done! we’ve seen how to configure Prettier to the Next.js project. I normally use VSCode with the Prettier plugin, and when I saved the modificated files, the semicolon and double quotes are automatically added. So, I decided to use Prettier in Next.js to solve this problem. If you have same problem, please try to add Prettier to your Next.js project.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts