Skip to main content

prettier

caution
# 直接格式化
npx prettier --write src/**/*.{ts,tsx,css,html}
# 格式检查
npx prettier --check src/**/*.{ts,tsx,css,html}

# 项目依赖
npm add -D prettier

# 当前配置文件
prettier --find-config-path src/types.d.ts

prettier --write src --cache --cache-strategy metadata


prettier --support-info
prettier --file-info a.js

prettier.config.js

// https://prettier.io/docs/en/options.html
module.exports = {
printWidth: 120,
singleQuote: true,
trailingComma: 'all',
};
package.json
{
"prettier": {
"bracketSameLine": false,
"importOrder": ["^[^.]", "^[.][.]", "^[.][/]"],
"importOrderSeparation": false,
"trailingComma": "all",
"printWidth": 120,
"singleQuote": true,
"overrides": [
{
"files": ["*.html", "*.css"],
"options": {
"singleQuote": false
}
}
]
},
"lint-staged": {
"**/*": "prettier --write --ignore-unknown"
}
}
配合 lint-staged
npm install --save-dev husky lint-staged
npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx lint-staged"

排序 import

npm add -D @trivago/prettier-plugin-sort-imports
module.exports = {
printWidth: 80,
tabWidth: 4,
trailingComma: 'all',
singleQuote: true,
jsxBracketSameLine: true,
semi: true,
importOrder: ['^@core/(.*)$', '^@server/(.*)$', '^@ui/(.*)$', '^[./]'],
};

plugins

  • prettier-plugin-sql
  • prettier-plugin-sh
  • prettier-plugin-pkg
    • package.json

ignore

  • .prettierignore
  • prettier-ignore 注释
// prettier-ignore
<div>
{/* prettier-ignore */}
<span ugly format='' />
</div>
<!-- prettier-ignore -->

SyntaxError: This experimental syntax requires enabling one of the following parser plugin(s): "decorators", "decorators-legacy".

importOrderParserPlugins: ['typescript', 'decorators-legacy'],

.prettierrc.json

{
"bracketSameLine": false,
"trailingComma": "all",
"printWidth": 120,
"singleQuote": true,
"jsxSingleQuote": true,
"overrides": [
{
"files": ["*.html", "*.css"],
"options": {
"singleQuote": false
}
},
{
"files": ["*.sql"],
"options": {
"tabWidth": 4
}
}
],
"importOrder": [
"^node:",
"<BUILTIN_MODULES>",
"[.](polyfill|shim)$",
"reflect-metadata",
"^react(-dom)?",
"<THIRD_PARTY_MODULES>",
"^@/",
"^[.][.]",
"^[.][/]"
],
"importOrderParserPlugins": ["typescript", "jsx", "decorators-legacy", "importAttributes"],
"plugins": ["prettier-plugin-pkg", "@ianvs/prettier-plugin-sort-imports", "prettier-plugin-tailwindcss"],
"tailwindFunctions": ["clsx", "tw", "cn"],
"tailwindConfig": "./tailwind.config.ts"
}

No parser could be inferred for file

cat abc.css | prettier --stdin-filepath abc.css