Setting up Prettier for Create React App

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 linting.

"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

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s