Prettier
An opinionated code formatter enforces a consistent code style across your entire codebase
Target
提交代碼時…
自動格式化代碼
使用 ESLint 檢查代碼,並自動修復錯誤
在修復不了的時候,回報錯誤(此次 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
.eslintrc
{
"extends": [
"plugin:prettier/recommended",
"prettier"
],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
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"
package.json
{
"lint-staged": {
"**/*": "prettier --write --ignore-unknown"
}
}
{
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"prettier --write",
"eslint --fix"
]
}
}
Additional
CI setup
Run prettier --check .
in CI to make sure that your project stays formatted.
prettier --check .
Reference
Last updated
Was this helpful?