概述
Prettier 是一个有主见的代码格式化程序,原生支持:
- JavaScript
- JSX
- Angular
- Vue
- Flow
- TypeScript
- CSS, Less, SCSS
- HTML
- Ember/Handlebars
- JSON
- GraphQL
- Markdown
- YAML
以及第三方维护的其他语言扩展
安装
安装前确保满足以下条件:
- nodejs,推荐使用最新版
- npm 镜像切换到国内,如,阿里云:
bash
# 查看当前源地址
npm config get registry
# 将源设为淘宝镜像
npm config set registry https://registry.npmmirror.com/
# 恢复默认
npm config set registry https://registry.npmjs.org
bash
# Prettier 安装到全局 [推荐]
npm i prettier -g
# Prettier 安装到项目中
pnpm add --save-dev --save-exact prettier
bash
# 创建一个空的配置文件,让编辑器和其他工具知道你正在使用Prettier
node --eval "fs.writeFileSync('.prettierrc','{}\n')"
# 创建一个.prettierignore文件,让Prettier CLI和编辑器知道哪些文件不需要格式化
node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')"
bash
# 使用Prettier格式化所有文件
pnpm exec prettier . --write
# 使用Prettier格式化 .vitepress/nav 和 .vitepress/sidebar 目录下的文件
pnpm exec prettier .vitepress/nav .vitepress/sidebar --write
# 格式化所有md和mts扩展的文件
pnpm exec prettier . "*.{md,mts}" --write
prettier 安装到全局的好处
- 不再不依赖项目本身,单文件也可以执行格式化
- sublime/vscode/PhpStorm 等编辑器 ide 可以通过环境变量,很容易获取到 prettier
- 如果单文件格式化也想要自定义配置,可以修改对应编辑器的 prettier 配置
配置文件优先级
- 项目根目录下
package.<json|yaml>
文件里的"prettier"
键 - 用 JSON 或 YAML 编写的
.prettierrc
文件 .prettierrc.<json|yml|yaml|json5>
文件- 使用
.prettierrc.js
或prettier.config.js
导出export default
或module.exports
对象的文件(取决于 type 中的 package.json 值) - 使用
.prettierrc.mjs
或prettier.config.mjs
导出export default
对象的文件 - 使用
.prettierrc.cjs
或prettier.config.cjs
导出module.exports
对象的文件 .prettierrc.toml
文件
配置覆盖
覆盖允许你针对特定扩展、文件夹以及特定文件拥有不同的配置
Prettier 参考了 ESLint 的覆盖格式
json
{
"semi": false,
"overrides": [
{
"files": "*.test.js",
"options": {
"semi": true
}
},
{
"files": ["*.html", "legacy/**/*.js"],
"options": {
"tabWidth": 4
}
}
]
}
yaml
semi: false
overrides:
- files: '*.test.js'
options:
semi: true
- files:
- '*.html'
- 'legacy/**/*.js'
options:
tabWidth: 4
设置解析器选项
默认情况下,Prettier 会根据输入文件的扩展名自动推断使用哪个解析器。结合 overrides
,你可以教 Prettier 如何解析它无法识别的文件。
例如,要让 Prettier 格式化自己的
.prettierrc
文件,您可以执行以下操作:json{ "overrides": [ { "files": ".prettierrc", "options": { "parser": "json" } } ] }
您也可以切换到
flow
解析器,而不是默认的.js 文件的babel
:json{ "overrides": [ { "files": "*.js", "options": { "parser": "flow" } } ] }
WARNING
注意:不要将 parser
选项放在配置的顶层。只能在 overrides
里面使用。否则,将禁用 Prettier 的自动文件扩展名为基础来推理解析器的功能。
parser
选项放在配置的顶层, 会强制 Prettier 使用您为所有类型的文件指定的解析器--即使它没有意义,比如试图将 CSS 文件解析为 JavaScript。
案例参考
json
{
"vueIndentScriptAndStyle": true,
"printWidth": 120,
"singleQuote": true,
"jsxSingleQuote": true,
"bracketSameLine": true,
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
},
{
"files": "*.(css|md)",
"options": {
"tabWidth": 4
}
},
{
"files": "*.(html|htm)",
"options": {
"htmlWhitespaceSensitivity": "ignore"
}
}
]
}
ini
# Ignore artifacts:
package.json
pnpm-lock.yaml
.vitepress/dist/
.vitepress/cache/
.vitepress/.temp/
json
{
// 保存文件时,是否格式化
"auto_format_on_save": true,
// 保存文件时,自动忽略的文件
// 全局通常不设置,针对项目设置根目录下的 .prettierignore 文件
"auto_format_on_save_excludes": [],
// Prettier 自定义配置
"prettier_options": {
"vueIndentScriptAndStyle": true,
"printWidth": 120,
"singleQuote": true,
"jsxSingleQuote": true,
"bracketSameLine": true,
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" },
},
{
"files": "*.(css|md)",
"options": {
"tabWidth": 4,
},
},
{
"files": "*.(html|htm)",
"options": {
"htmlWhitespaceSensitivity": "ignore",
},
},
],
},
}
json
{
"diffEditor.wordWrap": "off",
"diffEditor.codeLens": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"editor.cursorSmoothCaretAnimation": "on",
"editor.find.autoFindInSelection": "multiline",
// 控制编辑器是否自动折叠导入范围。
"editor.foldingImportsByDefault": true,
"editor.fontFamily": "'JetBrains Mono', '鸿蒙黑体', 'MiSans L3'",
"editor.fontLigatures": true,
"editor.fontSize": 14,
"editor.fontWeight": "400",
"editor.letterSpacing": 0,
"editor.formatOnPaste": true,
"editor.lineHeight": 1.5,
"editor.formatOnSave": true,
"editor.guides.bracketPairs": true,
"editor.lineNumbers": "relative",
"editor.linkedEditing": true,
"editor.mouseWheelZoom": true,
"editor.scrollbar.scrollByPage": true,
"editor.smoothScrolling": true,
"editor.suggest.insertMode": "replace",
"editor.suggestSelection": "recentlyUsedByPrefix",
"editor.tabCompletion": "onlySnippets",
"editor.tabSize": 2,
"editor.wordWrap": "on",
"editor.wordWrapColumn": 120,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"prettier.vueIndentScriptAndStyle": true,
"prettier.printWidth": 120,
"prettier.singleQuote": true,
"prettier.jsxSingleQuote": true,
"prettier.bracketSameLine": true,
"[php]": {
"editor.tabSize": 4,
"editor.defaultFormatter": "junstyle.php-cs-fixer"
},
"[markdown][css]": {
"editor.tabSize": 4,
"prettier.tabWidth": 4
},
"[html]": {
"prettier.htmlWhitespaceSensitivity": "ignore"
},
"workbench.enableExperiments": false,
"workbench.list.smoothScrolling": true,
"workbench.settings.editor": "json",
"workbench.settings.useSplitJSON": true,
"workbench.startupEditor": "none",
"window.closeWhenEmpty": true,
"window.menuBarVisibility": "classic",
"files.autoGuessEncoding": true,
"files.autoSave": "onFocusChange",
"files.eol": "auto",
"files.insertFinalNewline": false,
"files.trimFinalNewlines": true,
"files.trimTrailingWhitespace": true,
"explorer.incrementalNaming": "smart",
"search.actionsPosition": "auto",
"search.collapseResults": "auto",
"search.showLineNumbers": true,
"search.smartCase": true,
"update.mode": "manual",
"extensions.autoCheckUpdates": false,
"extensions.ignoreRecommendations": true,
"problems.showCurrentInStatus": true,
"todo-tree.highlights.defaultHighlight": {
"icon": "alert",
"foreground": "#ecf5ff",
"background": "#409eff",
"rulerColour": "#409eff",
"iconColour": "#409eff",
"rulerLane": "full",
"gutterIcon": true,
"type": "tag"
},
"todo-tree.highlights.customHighlight": {
"BUG": {
"foreground": "#000000",
"background": "#f56c6c",
"rulerColour": "#f56c6c",
"iconColour": "#f56c6c"
},
"TODO": {
"icon": "check"
},
"FIXME": {
"foreground": "#000000",
"background": "#FFFF00",
"rulerColour": "#FFFF00",
"iconColour": "#FFFF00"
}
},
// 使用 path-intellisense 禁用vscode自带路径智能感知
"typescript.suggest.paths": false,
"javascript.suggest.paths": false,
"markdown.suggest.paths.enabled": false,
"npm-intellisense.importLinebreak": ";\n",
"terminal.integrated.profiles.windows": {
"pwsh": {
"path": "C:\\sf\\pwsh\\pwsh.exe",
"icon": "terminal-powershell"
}
},
"terminal.external.windowsExec": "C:\\sf\\pwsh\\pwsh.exe",
"terminal.integrated.defaultProfile.windows": "pwsh",
"workbench.iconTheme": "material-icon-theme",
"update.showReleaseNotes": false,
"php-cs-fixer.executablePath": "C:\\php\\tools\\php-cs-fixer-v3.phar",
"php-cs-fixer.rules": "@PhpCsFixer",
// "php.validate.executablePath": "C:\\php\\84\\php.exe",
"editor.rulers": [
{
"column": 80,
"color": "#FFFF004D"
},
{
"column": 120,
"color": "#FFFFFF4D"
}
],
"files.associations": {
"*.sgml": "xml"
},
"extensions.experimental.affinity": {
"asvetliakov.vscode-neovim": 1
},
"diffEditor.hideUnchangedRegions.enabled": true,
"workbench.colorTheme": "One Dark Pro"
}