prettier+lint-staged+husky提交(commit)时格式化代码格式

安装依赖

yarn add prettier lint-staged husky -D;

执行命令

  1. npx husky install
  2. npx husky add .husky/pre-commit "npx lint-staged"
    在根目录下生成 .husky 文件夹;此文件是在commit时运行的检测脚本

添加 配置文件(.prettierrc.js) & 忽略文件(.prettierignore) (在 package.json 同级目录)

  • 配置文件(.prettierrc.js)
// .prettierrc.js
module.exports = {
    
    
  semi: true, // 使用分号, 默认true
  singleQuote: false, // 使用单引号, 默认false(在jsx中配置无效, 默认都是双引号)
  trailingComma: 'all', // 行尾逗号,默认none,可选 none|es5|all
  printWidth: 200,
  tabWidth: 2, // tab缩进大小,默认为2
  useTabs: false, // 使用tab缩进,默认false
  quoteProps: 'consistent',
  bracketSpacing: true,
  arrowParens: 'always',
  htmlWhitespaceSensitivity: 'ignore',
  vueIndentScriptAndStyle: true,
}
  • 忽略文件(.prettierignore)
// .prettierignore
.DS_Store
node_modules
/dist
/dist.zip
/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?

修改 package.json 配置

"lint-staged": {
    
    
    "*.{js,css,html,json,vue}": [
          "prettier --config .prettierrc.js --write",
          "git add"
      ]
  },
  "husky": {
    
    
      "hooks": {
    
    
          "pre-commit": "lint-staged"
      }
  },

  • 至此配置就完成了,当执行 git commit 时,prettier就会执行代码格式化

优化

添加校验命令

添加 (package.json) 方便执行检验项目所有文件排版格式;

"scripts": {
    
    
    "lint:prettier": "npx prettier --config ./.prettierrc.js --ignore-path ./.prettierignore --write **/*.{js,css,html,json,vue,jsx,tsx}"
 }

上传.sh .husky 生成命令生成的脚本

  • 将命令生成文件下的忽略文件 /.husky/_/.gitignore 文件删除或做对应的修改;

猜你喜欢

转载自blog.csdn.net/cc_King/article/details/130623944