Prettier

In this section, we will introduce Prettier, a code formatter that helps you write consistent code.

You can find the Prettier documentation here.

What is Prettier?

Prettier is a code formatter that formats your code according to a set of rules. It is designed to be opinionated, which means that Prettier takes care of most formatting decisions for you, allowing you to focus on writing code rather than debating about style choices.

Prettier supports many languages and file formats, including JavaScript, TypeScript, CSS, HTML, JSON, and more. It integrates well with most code editors.

Why Use Prettier?

  1. It helps you write consistent code.
  2. It catches common mistakes before they cause problems in your code.
  3. It ensures consistency in your code style, which is especially important when working in teams.

Installing and Setting Up Prettier

You may already be using the VSCode Prettier extension that automatically formats your files.

Now we will see how to use the Prettier npm package.

  1. Open your terminal or command prompt.
  2. Make sure you’re in the root of your project.
  3. Run the following command:
sh
	npm install -D prettier@3

The -D flag installs the package as a dev dependency. This is a shorthand and equivalent to --save-dev.

Prettier does not create a configuration file for us, so we need to create one ourselves. Create a file named .prettierrc in the root of your project and add the following:

json
	{
	  "semi": true,
	  "singleQuote": false
	}

Prettier supports a wide range of configuration options. You can find the full list of options here.

Running Prettier

Once you’ve installed and configured Prettier, you can run it in several ways.

To see these commands in action, disable the VSCode extension if you are using it, break the formatting in one or more files, and then:

  • Run Prettier on the entire project:
sh
	npx prettier . --write

The --write flag will format and save the files.

  • Run Prettier on a specific file:
sh
	npx prettier --write myFolder/myFile.js
  • Run Prettier on a specific directory:
sh
	npx prettier --write myFolder/

Prettier also supports glob patterns, which are a way to match multiple files with a single pattern. For example, to run Prettier on all JavaScript files in a folder, you can use the following command:

sh
	npx prettier --write myFolder/**/*.js