如何为next项目添加prettier并配置husky

前端 潘老师 5个月前 (11-26) 154 ℃ (0) 扫码查看

本文主要讲解关于如何为next项目添加prettier并配置husky 相关内容,让我们来一起学习下吧!

使用npx create-next-app@latest初始化项目时会有添加eslint的选项,一般都会选择启用,因此不用自己配置eslint。下面介绍如何在此基础上添加prettier和husky

安装prettier

npm i -D prettier eslint-config-prettier 

如果在next初始化时选择了启用tailwind,还可额外安装tailwind的扩展,可以自动排列className的顺序


# 额外的插件
npm i -D prettier-plugin-tailwindcss

.eslintrc.json中添上prettier扩展,让eslint和prettier能和谐使用

{
  "extends": ["next/core-web-vitals", "prettier"],
}

在更目录下创建.prettierrc.json,对prettier进行配置

{
  "plugins": [
    "prettier-plugin-tailwindcss"
  ],
  "tailwindFunctions": ["classNames"],
  "singleQuote": true,
  "trailingComma": "es5"
}

在package.json中加入format命令和check-format命令。format用于手动格式化代码,而check-format则用于下文的husky配置

...
  "scripts": {
    "check-format": "prettier --check "**/*.{js,jsx,ts,tsx}"",
    "format": "prettier --write "**/*.{js,jsx,ts,tsx}" && next lint --fix",
  }
...

如果有保存时自动格式化代码的需求,可以通过File > Preferences > Settings进入设置页面,搜索format on开启下列面这个选项

配置husky

安装husky和相关依赖

npm install --save-dev husky @commitlint/cli @commitlint/config-conventional

使用husky规范commit提交注释

初始化husky

npx husky install

添加提交git的hook

npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'

在项目根目录新建配置文件commitlint.config.js并添加如下配置

module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-case': [2, 'always', ['lower-case', 'upper-case']],
    'type-enum': [2, 'always',['feat', 'fix', 'docs','style','refactor','perf','test', 'chore', 'revert']]
  }
}

注:提交规范为<type>(<scope>): <subject>,type可选类型为上文type-enum中配置的关键字。subject 是本次提交的基本信息。前俩者为必填项,为选填项,用来描述本次提交的影响面。

提交示例:

#添加新特性的commit
git commit -m 'feat: xxx'  
# 修复bug的commit
git commit -m 'fix: xxx'

编写pre-commit

运行npx husky install后会在根目录生成一个.husky文件夹,文件夹下有一个pre-commit文件,我们可以在里面写一些shell脚本,这个脚本会在git commit执行前运行,因此我们可以在这个阶段进行测试代码、检验代码格式等操作。

如果没有该文件可以运行下列命令进行生成

npx husky add .husky/pre-commit

pre-commit编写示例:

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

echo '?️? commit前置操作'

echo '?代码格式检查'
# Check Prettier standards
npm run check-format ||
(
    echo '?? 代码格式有问题!';
    false;
)

echo '?lint检查'
npm run lint ||
(
    echo 'lint 校验失败!好好检查一下再提交 ?'
    false; 
)

echo '?ts代码校验'
npm run check-types ||
(
    echo '❌存在typescript相关错误!?'
    false; 
)

以上就是关于如何为next项目添加prettier并配置husky 相关的全部内容,希望对你有帮助。欢迎持续关注潘子夜个人博客(www.panziye.com),学习愉快哦!


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/front/11876.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】