话不多说,直接上步骤:
1、安装husky
pnpm install husky -D
2、在 package.json 的 script 添加命令
"scripts": {"prepare": "husky install"
}
3、执行 pnpm run prepare
执行完项目根目录也会出现一个.husky文件夹
4、安装lint-staged
pnpm install lint-staged -D
5、配置 package.json
{"lint-staged": {"**/*.{js,jsx,ts,tsx,vue,json,md}": "eslint --fix --ignore-path .gitignore"}
}
6、在 .husky 文件下建立 pre-commit 文件
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"pnpm exec lint-staged
7、安装
pnpm i @commitlint/cli @commitlint/config-conventional @esbuild-kit/cjs-loader -D
8、在 .husky 文件下建立 commit-msg 文件
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"pnpm exec commitlint --config commitlint.config.js --edit "${1}"
附:commitlint.config.ts 和 commitlint.config.js
// commitlint.config.ts
import { execSync } from 'child_process'
import fg from 'fast-glob'const getPackages = (packagePath) =>fg.sync('*', { cwd: packagePath, onlyDirectories: true })const scopes = [...getPackages('packages'),...getPackages('internal'),'docs','style','ci','var','ssr',
]const gitStatus = execSync('git status --porcelain || true').toString().trim().split('\n')const scopeComplete = gitStatus.find((r) => ~r.indexOf('M packages'))?.replace(/\//g, '%%')?.match(/packages%%((\w|-)*)/)?.[1]export default {rules: {/*** type[scope]: [function] description* ^^^^^*/'scope-enum': [2, 'always', scopes],/*** type[scope]: [function] description** ^^^^^^^^^^^^^^ empty line.* - Something here*/'body-leading-blank': [1, 'always'],/*** type[scope]: [function] description** - something here** ^^^^^^^^^^^^^^*/'footer-leading-blank': [1, 'always'],/*** type[scope]: [function] description [No more than 72 characters]* ^^^^^*/'header-max-length': [2, 'always', 72],'scope-case': [2, 'always', 'lower-case'],'subject-case': [1,'never',['sentence-case', 'start-case', 'pascal-case', 'upper-case'],],'subject-empty': [2, 'never'],'subject-full-stop': [2, 'never', '.'],'type-case': [2, 'always', 'lower-case'],'type-empty': [2, 'never'],/*** type[scope]: [function] description* ^^^^*/'type-enum': [2,'always',['build','chore','ci','docs','feat','fix','perf','refactor','revert','release','style','test','improvement',],],},prompt: {defaultScope: scopeComplete,customScopesAlign: !scopeComplete ? 'top' : 'bottom',allowCustomIssuePrefixs: false,allowEmptyIssuePrefixs: false,},
}
// commitlint.config.js
// commitlint uses `ts-node` to load typescript config, it's too slow. So we replace it with `esbuild`.
require('@esbuild-kit/cjs-loader')
module.exports = require('./commitlint.config.ts').default
然后试试提交代码,应该可以了!