Linting CSS in Create React App project

Install dependencies

# Yarn
yarn add -D stylelint stylelint-config-standard

# NPM
npm install -D stylelint stylelint-config-standard

Configure your stylelint

"stylelint": {
  "extends": [
    "stylelint-config-standard"
  ]
}

Add script to your package.json

"lint:css": "stylelint src/**/*.css"

Stylelint with Prettier

Install dependencies

# Yarn
yarn add -D stylelint-prettier stylelint-config-prettier

# NPM
npm install -D stylelint-prettier stylelint-config-prettier

Configure your stylelint with prettier rules

"stylelint": {
  "extends": [
    "stylelint-config-standard",
    "stylelint-prettier/recommended"
  ]
}

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"
    ]
  }