prettier格式化代码
2023年8月5日大约 1 分钟
prettier格式化代码
# 安装
yarn add -D lint-staged prettier husky
# 或者
pnpm add -D lint-staged prettier husky
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"
忽略文件(.prettierignore)
.DS_Store
node_modules
dist
/yarn.lock
/package-lock.json
/public/luckysheet
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
配置文件(.prettierrc.js)
// Prettier配置文档:https://prettier.io/docs/en/options.html
module.exports = {
printWidth: 90,
tabWidth: 4,
useTabs: true,
semi: true, // 结尾分号
singleQuote: false, // 使用单引号
quoteProps: "as-needed", //仅在必需时为对象的key添加引号
trailingComma: "es5", // 属性值 es5 表示在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar }
bracketSameLine: false,
arrowParens: "always", //单参数箭头函数参数周围使用圆括号-eg: (x) => x
proseWrap: "preserve",
htmlWhitespaceSensitivity: "ignore", // 标签换行不完整问题
vueIndentScriptAndStyle: false,
embeddedLanguageFormatting: "auto",
singleAttributePerLine: false, //属性单独成行
};
package.json
配置
"lint-staged": {
"path/**/*.{js,vue}": [
"prettier --config .prettierrc.js --write './*.{js,vue}'"
]
}
注意
- Prettier 只支持 ES 模块
删除 package.json
中的 "type": "module"
配置
- 在 commit 之前,会运行 lint-staged, 校验 js 代码。这一步如果有错误,你的代码会被放到暂存区。
所以你的新代码都没啦。
但是不要慌,这个时候,我们运行 git stash apply,把暂存区的代码放出来就行了。