Prettier

An opinionated code formatter enforces a consistent code style across your entire codebase

Target

提交代碼時…

  1. 自動格式化代碼

  2. 使用 ESLint 檢查代碼,並自動修復錯誤

  3. 在修復不了的時候,回報錯誤(此次 commit 不會提交)

Basic Configuration

.prettierrc

{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "always",
  "proseWrap": "preserve"
}

Install

yarn add -D prettier

package.json

{
  "scripts": {
    "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\""
  }
}
{
  "scripts": {
    "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\" \"test/**/*.ts\""
  }
}

Integrating with ESLint Linters

If you use ESLint, install eslint-config-prettier to make ESLint and Prettier play nice with each other. It turns off all ESLint rules that are unnecessary or might conflict with Prettier.

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

eslint-config-prettier: 關閉所有不必要或可能跟 Prettier 產生衝突的規則。 eslint-plugin-prettier: 可以讓 ESLint 使用 Prettier 規則進行檢查,並使用 --fix 選項。

.eslintrc

{
  "extends": [
    "plugin:prettier/recommended",
    "prettier"
  ],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}

使 eslint-config-prettier 生效。覆蓋 ESLint 中與 Prettier 衝突的配置。 使 eslint-plugin-prettier 生效,不符合 prettier/prettier 的規則會報錯。

Git Pre-commit Hooks

Run Prettier as a pre-commit hook to makes sure all your commits are formatted.

yarn add -D husky lint-staged

npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx lint-staged"

husky: Git hooks,這裡主要用 pre-commit 鉤子,在 commit 之前幫你做一些事情。 lint-staged: 在提交的文件中,執行自定義的指令。

package.json

{
  "lint-staged": {
    "**/*": "prettier --write --ignore-unknown"
  }
}
{
  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx}": [
      "prettier --write",
      "eslint --fix"
    ]
  }
}

Note: If you use ESLint, make sure lint-staged runs it before Prettier, not after.

Additional

CI setup

Run prettier --check . in CI to make sure that your project stays formatted.

prettier --check .

--check is like --write, but only checks that files are already formatted, rather than overwriting them.

Reference

Last updated

Was this helpful?