代码格式化
项目代码格式化,有利于形成统一的前端代码规范,利于团队开发和项目进展
简单搭建项目环境
初始化项目
mkdir test-project
npm init
git init
添加.gitignore
/node_modules
创建单个文件 scr/App.tsx
function Name(){
console.log('我是你爹')
}
代码开发 eslint + lint-staged
pnpm i eslint -D
pnpm init @eslint/config
选择自己需要的配置
// package.json添加命令
"eslint": "eslint src/**/*.{ts,tsx}"
执行lint命令 解决lint报错
npm run eslint
引入lint-staged优化 eslint 检测速度
// package.json修改lint 命令
"eslint": "eslint"
// package.json添加lint-staged配置
"lint-staged": {
"src/**/*.{ts,tsx}": [
"npm run eslint"
]
},
代码提交 git 规范 husky + commitlint + commitizen
husky: 会在git提交代码时对代码语法进行检测,只有检测通过时才能被提交 commitlint: 在提交代码时,良好的提交备注会方便多人开发时其他人理解本次提交修改的大致内容,也方便后面维护迭代,但每个人习惯都不一样,需要用工具来做下限制,[commitlint]就是用来验证git commit的备注是否符合定义的规范 commitizen: 交互式生成commit的备注信息
配置
// 安装husky
pnpm i husky -D
// 配置pre-commit
npx husky install
npx husky add .husky/pre-commit 'npm run pre-check'
// 安装和配置 commitlint
pnpm i @commitlint/config-conventional @commitlint/cli -D
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
// 安装 commitizen
pnpm i commitizen -g // 全局安装后 可以执行git cz命令
pnpm i cz-customizable -D // 项目内安装
// 添加配置到 **package.json**
"config": {
"commitizen": {
"path": "./node_modules/cz-customizable"
}
}
配置**.cz-config.js** 自定义提示文件
module.exports = {
// 可选类型,和上面commitlint.config.js配置的规则一一对应
types: [
{ value: 'feat', name: 'feat: 新功能' },
{ value: 'fix', name: 'fix: 修复' },
{ value: 'docs', name: 'docs: 文档变更' },
{ value: 'style', name: 'style: 代码格式(不影响代码运行的变动)' },
{ value: 'refactor', name: 'refactor: 重构(既不是增加feature,也不是修复bug)' },
{ value: 'perf', name: 'perf: 性能优化' },
{ value: 'test', name: 'test: 增加测试' },
{ value: 'chore', name: 'chore: 构建过程或辅助工具的变动' },
{ value: 'revert', name: 'revert: 回退' },
{ value: 'build', name: 'build: 打包' }
], // 消息步骤,正常只需要选择
messages: {
type: '请选择提交类型:', // customScope: '请输入修改范围(可选):',
subject: '请简要描述提交(必填):', // body: '请输入详细描述(可选):',
footer: '请输入要关闭的issue(可选):',
confirmCommit: '确认使用以上信息提交?(y/n)'
}, // 跳过问题:修改范围,自定义修改范围,详细描述,issue相关
skipQuestions: ['scope', 'customScope', 'body', 'footer'], // subject描述文字长度最长是72
subjectLimit: 72
}
验证效果
git add .
git cz
效果如下