Dávid Szabó
Dave is Coding

Dave is Coding

Setting up Prettier in a Create React App project

Dávid Szabó's photo
Dávid Szabó
·Dec 20, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Install dependencies

# Yarn
yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

# NPM
npm install -D prettier eslint-config-prettier eslint-plugin-prettier

By default your eslintConfig looks like this:

"eslintConfig": {
    "extends": [
        "react-app",
        "react-app/jest"
    ]
}

Let’s add Prettier and Prettier React to the extends array:

"eslintConfig": {
    "extends": [
        "react-app",
        "react-app/jest",
        "plugin:prettier/recommended",
        "prettier/react"
    ]
}

Your editor should pick up the eslint config change after saving package.json. Let’s add two scripts to our package.json, one for formatting and one for lining.

"format:js": "prettier --write src/**/*.{js,jsx,ts,tsx}",
"lint:js": "eslint src/**/*.{js,jsx,ts,tsx}"

(NOTE: I used js,jsx,ts,tsx in the patterns above. If you don’t have any files that match any of those patterns, then you will get an error. Feel free to remove extensions that you aren’t using)

If you are using TypeScript then you might want to add type checking to the lint script as well:

"lint:js": "tsc --noEmit && eslint src/**/*.{js,jsx,ts,tsx}"

Automagically lint before git commit

You might want to automatically run the lint script before git commits. This can be achieved easily by using husky and lint-staged. Let’s start by installing them as dev dependencies:

# Yarn
yarn add -D husky lint-staged

# NPM
npm install -D husky lint-staged
```bash

Next you just need to add a few lines to your package.json:

```json
"husky": {
    "hooks": {
        "pre-commit": "lint-staged"
    }
},
"lint-staged": {
    "src/**/*.{js,jsx,ts,tsx}": [
        "yarn lint:js"
    ]
}
 
Share this