前端项目规范化:手把手教你使用prettier和pre-commit(git hook或者husky)优化规范项目代码

如何在提交代码之前,进行代码格式化检查,保证每个成员的代码都是同一个风格呢?

最简单的两种方式:

    1. 使用 prettier + git pre-commit
    1. 使用 prettier + husky(原理和第一种一模一样哦)

名词简介

git hooks

下图为git hooks的官方示例,以.sample结尾。注意这些以.sample结尾的示例脚本是不会执行的,重命名后会生效

  • 是一些自定义的脚本,用于控制git工作的流程,分为客户端钩子和服务端钩子。

  • 客户端钩子包括:pre-commit、prepare-commit-msg、commit-msg、post-commit等,主要用于控制客户端git的提交工作流。服务端钩子:pre-receive、post-receive、update,主要在服务端接收提交对象时、推送到服务器之前调用。

  • git hooks位置位于每个git项目下的隐藏文件夹.git中的hooks文件夹里

  • 具体内容可以参考git的文档

Git pre-commit

  • 客户端hooks之一,在git add提交之后,然后执行git commit时执行,脚本执行没有问题的话就继续提交,反之就驳回提交操作
  • 它一般用来对将要提交的代码进行检查、优化代码格式、或者对提交的图片进行压缩等等任务
    举个栗子,下面是eslint检查的一个shell脚本,将下面代码保存为.git/hooks/pre-commit中,每次执行git commit时就会使用eslint进行代码检查
STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.vue' '*.js')
if test ${#STAGE_FILES} -gt 0
then
echo '开始eslint检查'
which eslint &> /dev/null
if [[ "$?" == 1 ]]; then
echo '没安装eslint'
exit 1
fi
PASS=true
for FILE in $STAGE_FILES
do
eslint $FILE
if [[ "$?" == 1 ]]; then
PASS=false
fi
done
if ! $PASS; then
echo "eslint检查没通过!"
exit 1
else
echo "eslint检查完毕"
fi
else
echo '没有js文件需要检查'
fi
exit 0
STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.vue' '*.js')
if test ${#STAGE_FILES} -gt 0


then


    echo '开始eslint检查'



    which eslint &> /dev/null
    if [[ "$?" == 1 ]]; then
        echo '没安装eslint'
        exit 1
    fi



    PASS=true



    for FILE in $STAGE_FILES
    do
        eslint $FILE
        if [[ "$?" == 1 ]]; then
      PASS=false
    fi
  done

  if ! $PASS; then
      echo "eslint检查没通过!"
      exit 1
  else
      echo "eslint检查完毕"
  fi

else
    echo '没有js文件需要检查'
fi

exit 0
STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.vue' '*.js') if test ${#STAGE_FILES} -gt 0 then echo '开始eslint检查' which eslint &> /dev/null if [[ "$?" == 1 ]]; then echo '没安装eslint' exit 1 fi PASS=true for FILE in $STAGE_FILES do eslint $FILE if [[ "$?" == 1 ]]; then PASS=false fi done if ! $PASS; then echo "eslint检查没通过!" exit 1 else echo "eslint检查完毕" fi else echo '没有js文件需要检查' fi exit 0

prettier

  • prettier是一个代码格式化工具,它可以支持JS/JSX/TS/Flow/JSON/CSS/LESS等文件格式。
  • 用来优化代码格式,比如缩进、空格、分号等等

husky

可以用于实现各种 Git Hook。这里主要用到 pre-commit这个 hook,在执行 commit 之前,运行一些自定义操作

快速上手第一种方案:使用 prettier + git pre-commit 检查并格式化本次修改的文件

本文示例代码

安装依赖到开发环境

//npm
npm install --save-dev --save-exact prettier
//yarn
yarn add --dev --exact prettier
//npm

npm install --save-dev --save-exact prettier

//yarn

yarn add --dev --exact prettier
//npm npm install --save-dev --save-exact prettier //yarn yarn add --dev --exact prettier

根目录下创建.prettierrc.js

  • .prettierrc 文件用于配置规则,
module.exports = {
printWidth: 100, // 单行长度
tabWidth: 2, // 缩进长度
useTabs: false, // 使用空格代替tab缩进
semi: true, //句末使用分号
singleQuote: true, //使用单引号
quoteProps: 'as-needed', //仅在必需时为对象的key添加引号
trailingComma: 'all', //多行时尽可能打印尾随逗号
bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar }
jsxBracketSameLine: true, //多属性html标签的‘>’折行放置
arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x
requirePragma: false, //无需顶部注释即可格式化
insertPragma: false, //在已被preitter格式化的文件顶部加上标注
proseWrap: 'preserve', //不知道怎么翻译
htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感
endOfLine: 'lf', //结束行形式
embeddedLanguageFormatting: 'auto', //对引用代码进行格式化
};
module.exports = {

  printWidth: 100, // 单行长度

  tabWidth: 2, // 缩进长度

  useTabs: false, // 使用空格代替tab缩进

  semi: true, //句末使用分号

  singleQuote: true, //使用单引号

  quoteProps: 'as-needed', //仅在必需时为对象的key添加引号

  trailingComma: 'all', //多行时尽可能打印尾随逗号

  bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar }

  jsxBracketSameLine: true, //多属性html标签的‘>’折行放置

  arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x

  requirePragma: false, //无需顶部注释即可格式化

  insertPragma: false, //在已被preitter格式化的文件顶部加上标注

  proseWrap: 'preserve', //不知道怎么翻译

  htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感

  endOfLine: 'lf', //结束行形式

  embeddedLanguageFormatting: 'auto', //对引用代码进行格式化

};
module.exports = { printWidth: 100, // 单行长度 tabWidth: 2, // 缩进长度 useTabs: false, // 使用空格代替tab缩进 semi: true, //句末使用分号 singleQuote: true, //使用单引号 quoteProps: 'as-needed', //仅在必需时为对象的key添加引号 trailingComma: 'all', //多行时尽可能打印尾随逗号 bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar } jsxBracketSameLine: true, //多属性html标签的‘>’折行放置 arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x requirePragma: false, //无需顶部注释即可格式化 insertPragma: false, //在已被preitter格式化的文件顶部加上标注 proseWrap: 'preserve', //不知道怎么翻译 htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感 endOfLine: 'lf', //结束行形式 embeddedLanguageFormatting: 'auto', //对引用代码进行格式化 };

根目录下创建.prettierignore,忽略不想格式化的文件

  • .prettierignore 文件用于忽略默写不需要处理的文件或目录
  • node_modules默认被忽略,创建 .prettierignore忽略其他文件
build
.cache
# Ignore all HTML files:
*.html
*.yml
*.yaml
build

.cache



# Ignore all HTML files:

*.html

*.yml

*.yaml
build .cache # Ignore all HTML files: *.html *.yml *.yaml

手动测试格式化效果

举个栗子:我们先故意把./index.js文件搞乱,然后测试格式化./index.js

npx prettier --write ./index.js
//或
yarn prettier --write ./index.js
npx prettier --write ./index.js

//或



yarn prettier --write ./index.js
npx prettier --write ./index.js //或 yarn prettier --write ./index.js

备注:格式化全部文件的命令

npx prettier --write .
//或
yarn prettier --write .
npx prettier --write .

//或



yarn prettier --write .
npx prettier --write . //或 yarn prettier --write .

配置Git提交代码 Commit 前执行 Prettier (只格式化本次改动的文件)

创建 .git/hooks/pre-commit

STAGE_FILES=$(git diff --cached --name-only -- '*.json' '*.js')
if test ${#STAGE_FILES} -gt 0
then
echo '开始代码格式检查与修正'
for FILE in $STAGE_FILES
do
npx prettier --write $FILE
if [[ "$?" == 1 ]]; then
PASS=false
fi
done
echo "代码格式化检查完毕"
else
echo '没有js或者json文件需要检查'
fi
exit 0
STAGE_FILES=$(git diff --cached --name-only -- '*.json' '*.js')

if test ${#STAGE_FILES} -gt 0


then


    echo '开始代码格式检查与修正'

    for FILE in $STAGE_FILES

    do

        npx prettier --write $FILE

        if [[ "$?" == 1 ]]; then

      PASS=false

    fi


  done

echo "代码格式化检查完毕"




else

    echo '没有js或者json文件需要检查'

fi



exit 0
STAGE_FILES=$(git diff --cached --name-only -- '*.json' '*.js') if test ${#STAGE_FILES} -gt 0 then echo '开始代码格式检查与修正' for FILE in $STAGE_FILES do npx prettier --write $FILE if [[ "$?" == 1 ]]; then PASS=false fi done echo "代码格式化检查完毕" else echo '没有js或者json文件需要检查' fi exit 0

改动部分文件,进行测试

把代码改乱,然后执行下面命令

git add .
git commit -m "feat: test pre commit prettier"
git add .
git commit -m "feat: test pre commit prettier"
git add . git commit -m "feat: test pre commit prettier"

代码已被修正,修正后,我们需要重新执行命令再次提交

按需处理文件

当我们提交非 js ,json文件时候,会提示:没有js或者json文件需要检查

XXX prettier-demo % git add .
git commit -m "feat: add readme"
没有js或者json文件需要检查
[master 262be83] feat: add readme
1 file changed, 21 insertions(+)
create mode 100644 README.md
XXX prettier-demo %
XXX prettier-demo % git add .

git commit -m "feat: add readme"             
没有js或者json文件需要检查
[master 262be83] feat: add readme
 1 file changed, 21 insertions(+)
 create mode 100644 README.md



XXX prettier-demo % 
XXX prettier-demo % git add . git commit -m "feat: add readme" 没有js或者json文件需要检查 [master 262be83] feat: add readme 1 file changed, 21 insertions(+) create mode 100644 README.md XXX prettier-demo %

方案一大功告成

快速上手第二种方案:使用 prettier + husky 检查并格式化本次修改的文件

友情提示,此部分内容几乎和第一种一样,但是用了husky,没有使用git hook

安装依赖到开发环境

//npm
npm install --save-dev --save-exact prettier
//yarn
yarn add --dev --exact prettier
//npm

npm install --save-dev --save-exact prettier

//yarn

yarn add --dev --exact prettier
//npm npm install --save-dev --save-exact prettier //yarn yarn add --dev --exact prettier

根目录下创建.prettierrc.js

  • .prettierrc 文件用于配置规则,
module.exports = {
printWidth: 100, // 单行长度
tabWidth: 2, // 缩进长度
useTabs: false, // 使用空格代替tab缩进
semi: true, //句末使用分号
singleQuote: true, //使用单引号
quoteProps: 'as-needed', //仅在必需时为对象的key添加引号
trailingComma: 'all', //多行时尽可能打印尾随逗号
bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar }
jsxBracketSameLine: true, //多属性html标签的‘>’折行放置
arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x
requirePragma: false, //无需顶部注释即可格式化
insertPragma: false, //在已被preitter格式化的文件顶部加上标注
proseWrap: 'preserve', //不知道怎么翻译
htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感
endOfLine: 'lf', //结束行形式
embeddedLanguageFormatting: 'auto', //对引用代码进行格式化
};
module.exports = {

  printWidth: 100, // 单行长度

  tabWidth: 2, // 缩进长度

  useTabs: false, // 使用空格代替tab缩进

  semi: true, //句末使用分号

  singleQuote: true, //使用单引号

  quoteProps: 'as-needed', //仅在必需时为对象的key添加引号

  trailingComma: 'all', //多行时尽可能打印尾随逗号

  bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar }

  jsxBracketSameLine: true, //多属性html标签的‘>’折行放置

  arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x

  requirePragma: false, //无需顶部注释即可格式化

  insertPragma: false, //在已被preitter格式化的文件顶部加上标注

  proseWrap: 'preserve', //不知道怎么翻译

  htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感

  endOfLine: 'lf', //结束行形式

  embeddedLanguageFormatting: 'auto', //对引用代码进行格式化

};
module.exports = { printWidth: 100, // 单行长度 tabWidth: 2, // 缩进长度 useTabs: false, // 使用空格代替tab缩进 semi: true, //句末使用分号 singleQuote: true, //使用单引号 quoteProps: 'as-needed', //仅在必需时为对象的key添加引号 trailingComma: 'all', //多行时尽可能打印尾随逗号 bracketSpacing: true, //在对象前后添加空格-eg: { foo: bar } jsxBracketSameLine: true, //多属性html标签的‘>’折行放置 arrowParens: 'always', //单参数箭头函数参数周围使用圆括号-eg: (x) => x requirePragma: false, //无需顶部注释即可格式化 insertPragma: false, //在已被preitter格式化的文件顶部加上标注 proseWrap: 'preserve', //不知道怎么翻译 htmlWhitespaceSensitivity: 'ignore', //对HTML全局空白不敏感 endOfLine: 'lf', //结束行形式 embeddedLanguageFormatting: 'auto', //对引用代码进行格式化 };

根目录下创建.prettierignore,忽略不想格式化的文件

  • .prettierignore 文件用于忽略默写不需要处理的文件或目录
  • node_modules默认被忽略,创建 .prettierignore忽略其他文件
build
.cache
# Ignore all HTML files:
*.html
*.yml
*.yaml
build

.cache



# Ignore all HTML files:

*.html

*.yml

*.yaml
build .cache # Ignore all HTML files: *.html *.yml *.yaml

手动测试格式化效果

举个栗子:我们先故意把./index.js文件搞乱,然后测试格式化./index.js

npx prettier --write ./index.js
//或
yarn prettier --write ./index.js
npx prettier --write ./index.js

//或



yarn prettier --write ./index.js
npx prettier --write ./index.js //或 yarn prettier --write ./index.js

备注:格式化全部文件的命令

npx prettier --write .
//或
yarn prettier --write .
npx prettier --write .

//或



yarn prettier --write .
npx prettier --write . //或 yarn prettier --write .

安装husky

npm install husky --save-dev
npm install husky --save-dev
npm install husky --save-dev

让 husky 启用 git hooks

npx husky install
npx husky install
npx husky install

执行完之后文件根目录会多一个 .husky 文件夹:

设置安装后自动启用 git hooks

==注意:yarn 安装是不支持 prepare 这个生命周期的,需要将 prepare 改成 postinstall==

npm set-script prepare "husky install"
npm set-script prepare "husky install"
npm set-script prepare "husky install"

可以看到 package.json 里增加一个 script

创建 pre commit hook

// 下面这行命令后面没有跟脚本,会产生undefined 的内容,但是我们可以自己修改具体的脚本命令
npx husky add .husky/pre-commit
// 下面这行命令后面没有跟脚本,会产生undefined 的内容,但是我们可以自己修改具体的脚本命令
npx husky add .husky/pre-commit 
// 下面这行命令后面没有跟脚本,会产生undefined 的内容,但是我们可以自己修改具体的脚本命令 npx husky add .husky/pre-commit

.husky/pre-commit 写入脚本

STAGE_FILES=$(git diff --cached --name-only -- '*.json' '*.js')
if test ${#STAGE_FILES} -gt 0
then
echo '开始代码格式检查与修正'
for FILE in $STAGE_FILES
do
npx prettier --write $FILE
if [[ "$?" == 1 ]]; then
PASS=false
fi
done
echo "代码格式化检查完毕"
else
echo '没有js或者json文件需要检查'
fi
exit 0
STAGE_FILES=$(git diff --cached --name-only -- '*.json' '*.js')

if test ${#STAGE_FILES} -gt 0


then


    echo '开始代码格式检查与修正'

    for FILE in $STAGE_FILES

    do

        npx prettier --write $FILE

        if [[ "$?" == 1 ]]; then

      PASS=false

    fi


  done

echo "代码格式化检查完毕"




else

    echo '没有js或者json文件需要检查'

fi



exit 0
STAGE_FILES=$(git diff --cached --name-only -- '*.json' '*.js') if test ${#STAGE_FILES} -gt 0 then echo '开始代码格式检查与修正' for FILE in $STAGE_FILES do npx prettier --write $FILE if [[ "$?" == 1 ]]; then PASS=false fi done echo "代码格式化检查完毕" else echo '没有js或者json文件需要检查' fi exit 0

测试,大功告成

今天就写到这里啦~

  • 小伙伴们,( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ我们明天再见啦~~
  • 大家要天天开心哦

欢迎大家指出文章需要改正之处~
学无止境,合作共赢

在这里插入图片描述

欢迎路过的小哥哥小姐姐们提出更好的意见哇~~

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYPUbIs6' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片