Prettier setup

Prettier is an auto-formatter for JavaScript, CSS, Sass, GraphQL, Markdown, and many more. We encourage all projects to adopt Prettier.

How to set up Prettier

Add packages

Add the prettier package. (Please avoid the prettier-cli package and some others; see Deprecated packages for info.)

yarn add --dev prettier

Configure Prettier

Save a file called .prettierrc in your project's root path. This configuration roughly mimics the styling rules of Standard JS.

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

Add scripts

Add these scripts to package.json. Be sure to change the path globs.

"scripts": {
  "prettier:check": "prettier --list-different 'styles/**/*.scss' 'scripts/**/*.{js,jsx,ts,tsx}'",
  "prettier:fix": "prettier --write 'styles/**/*.scss' 'scripts/**/*.{js,jsx,ts,tsx}'"
}

Run in CI

Add prettier:check to CI. Here's an example for Semahpore CI:

if grep prettier:check package.json >/dev/null; then yarn run prettier:check; fi

Set up your editor

(Optional but highly recommended) Get everyone's {vscode,atom,emacs,vim} editors to run Prettier on save. See Editor Support on prettier.io

Gotchas

  • Be sure that you're linting the correct file types. For instance, you may need to include {ts,tsx} for TypeScript projects.

Interoperability with other tools

To use Prettier with other tools, you may need to install the corresponding x-config-prettier package for those tools. For instance:

  • Stylelint: Use stylelint-config-prettier, and add { "extends": [ "stylelint-config-prettier" ] } to your Stylelint config.

  • Eslint: Use eslint-config-prettier, and add { "extends": [ "eslint-config-prettier" ] } to your Eslint config.

  • Tslint: Use tslint-config-prettier, and add { "extends": [ "tslint-config-prettier" ] } to your Tslint config.

Deprecated practices

  • Avoid prettier-eslint, use x-config-prettier packages instead. (Jan 2019)
    This greatly simplifies our Prettier setup and makes Prettier integrate better into other tools.

  • Avoid prettier-cli, use prettier instead. (Jan 2019)
    This is to avoid the issue of yarn not being able to run the prettier command. Prettier's official docs on CLI.