Code Formatting with Prettier

Updated on
2 min read
Guide on
Table of contents

Prettier is an opinionated code formatter that formats the code in a consistent style. It supports popular languages, libraries, and frameworks in the Node.js ecosystem and is widely used to enforce the style practices.

In this post, we’ll integrate it with a Node.js application and explore on how to configure it to work with EditorConfig and ESLint.

Install Prettier

Execute the following command in the directory where package.json is located:

sh
yarn add -D -E prettier

As per the Prettier’s documentation, it is recommended to save an exact version of prettier in the package.json since it introduces stylistic changes in patch releases.

Configure pre-commit hook

To format the staged files before you commit them to git, you can use pretty-quick to run prettier on staged files and husky to configure a pre-commit hook.

Execute the following command to install dependencies.

sh
yarn add -D pretty-quick husky

Add an fmt script in package.json to format the staged files and configure the husky object with a hook.

json
{
  "scripts": {
    "fmt": "pretty-quick --staged"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run fmt"
    }
  }
}

Working with EditorConfig

EditorConfig is a popular way to maintain consistent coding styles between multiple developers across different editors and IDEs. It consists of a .editorconfig file that contains coding styles and a plugin that enables the editors and IDEs to enforce those styles.

An editorconfig file for an Angular application generated by Angular CLI looks like this:

ini
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false

Prettier CLI respects the editorconfig file by default. You can opt-out of this behavior using --no-editorconfig flag.

Working with ESLint

If you’re working on a JavaScript project, you can use ESLint to format your code with Prettier. Execute the following command to add necessary plugins.

sh
yarn add -D eslint-config-prettier eslint-plugin-prettier

Now, open the .eslintrc.json file and add the following configuration:

json
{
  "extends": [
    "plugin:prettier/recommended"
  ]
}
Share