为next项目添加prettier并配置husky

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

安装prettier

arduino 复制代码
npm i -D prettier eslint-config-prettier 

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

bash 复制代码
# 额外的插件
npm i -D prettier-plugin-tailwindcss

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

json 复制代码
{
  "extends": ["next/core-web-vitals", "prettier"],
}

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

json 复制代码
{
  "plugins": [
    "prettier-plugin-tailwindcss"
  ],
  "tailwindFunctions": ["classNames"],
  "singleQuote": true,
  "trailingComma": "es5"
}

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

erlang 复制代码
...
  "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和相关依赖

scss 复制代码
npm install --save-dev husky @commitlint/cli @commitlint/config-conventional

使用husky规范commit提交注释

初始化husky

复制代码
npx husky install

添加提交git的hook

sql 复制代码
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'

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

java 复制代码
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 是本次提交的基本信息。前俩者为必填项,为选填项,用来描述本次提交的影响面。

提交示例:

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

编写pre-commit

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

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

sql 复制代码
npx husky add .husky/pre-commit

pre-commit编写示例:

bash 复制代码
#!/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; 
)

参考文章

How To Style Your Next.JS Projects EXACTLY Like Google (in TypeScript)

新版husky8.0配合commitlint,规范我们的git的提交记录

如何给 Next.js 项目配置代码格式化和校验(ESLint + Prettier + husky)

相关推荐
Pedantic1 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘1 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
一颗烂土豆2 小时前
Meshopt 压缩深度解析,为什么它比 Draco 更快
前端·javascript·webgl
浏览器工程师3 小时前
AI Agent 接浏览器任务,先别让它一路点到底
前端·后端
雨季mo浅忆3 小时前
VSCode自动格式化三要素
前端
爱勇宝3 小时前
深扒 Anthropic 1680 位工程师简历:应届生几乎没机会,AI 公司最缺的不是博士
前端·后端·程序员
kyriewen4 小时前
同事每天催我 Code Review,我写了个脚本让 AI 替我 review PR——现在他反过来催 AI 了
前端·javascript·ai编程
user20585561518136 小时前
Windows 项目安装时报 `node-sass` 错误,如何快速处理
前端
LiaCode6 小时前
Redis 在生产项目的使用
前端·后端