前端项目代码规范搭建
代码规范是前端工程化中很重要的一环,这里对前端项目中代码规范的搭建做了一个总结
代码规范的搭建会使用到以下依赖:
- eslint
- styleLint
- prettier
- husky
- lint-staged
- commit-lint
大体的思路是:使用 Eslint做开发时的代码检查,使用Husky激活 GitHooks。配合 Prettier、Lint-Staged等依赖来做提交时的代码格式化和 Commit信息规范化
配置Eslint
这里采用腾讯的eslint-config-alloy规范,笔记中使用的是Typescript React规则,更多规则可以查看Git文档
- 安装依赖
npm install --save-dev eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react eslint-config-alloy
在你的项目根目录创建一个.eslintrc.js文件,并将以下内容复制进去:
module.exports = {
extends: [
'alloy',
'alloy/react',
'alloy/typescript',
],
env: {
// 你的环境变量(包含多个预定义的全局变量)
//
// browser: true,
// node: true,
// mocha: true,
// jest: true,
// jquery: true
},
globals: {
// 你的全局变量(设置为 false 表示它不允许被重新赋值)
//
// myGlobal: false
},
rules: {
// 自定义你的规则
},
};
重启编辑器即可生效,可以查看官方示例知道哪些代码是错误的。
配置.eslintignore文件来跳过某些不需要检查的文件
/src/.umi
/node_modules
/config
/public
/dist
配置stylelint
- 安装依赖
yarn add stylelint stylelint-config-prettier stylelint-config-standard -D
在项目根目录创建.stylelintrc.js文件
module.exports = {
extends: ['stylelint-config-standard', 'stylelint-config-prettier']
}
可以创建.stylelintrcignore文件来跳过某些不需要检查的文件
/src/.umi
/node_modules
/config
/public
/dist
prettier
prettier是一款代码格式化工具,可以通过零配置来实现代码的格式化
在项目根目录新建.prettierrc.js文件,写入以下规则
const alloyPrettier = require('eslint-config-alloy/.prettierrc.js');
// 导出config-alloy的配置
module.exports = {
...alloyPrettier,
};
可以创建.prettierignore文件跳过某些不需要检查的文件
**/*.md
**/*.svg
**/*.html
scripts
config
public
dist
zip
node_modules
git规范
git提供了很多Hooks,可以让我们在不同的阶段对代码进行不同的操作,控制提交到仓库的代码的规范性和准确性。husky是操作Git Hooks的工具,和它类似的工具还有yorkie
- pre-commit: 预提交,由git commit命令调用,可以通过
--no-verify参数绕过调用pre-commit。通常用于在提交代码前,进行代码规范检查。 - commit-message: 通常用于commit信息的校检
安装依赖
- 安装husky lint-staged
yarn add lint-staged husky -D
npm set-script prepare "husky install" # 在package.json中添加脚本
git init // 初始化git仓库,注意这个必须要在初始化husky之前
yarn prepare # 初始化husky,将 git hooks 钩子交由,husky执行
配置pre-commit
npx husky add .husky/pre-commit "npx lint-staged"
配置commit-msg
- 安装依赖
yarn add commitlint @commitlint/config-conventional -D
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"' # 创建commit-msg
这里使用的是Angular的commit规范
| 类型 | 描述 |
|---|---|
| feat | 新功能 |
| fix | 修补BUG |
| refactor | 代码重构 |
| style | 代码格式更改 |
| perf | 代码优化相关,如提升性能,体验 |
| docs | 文档更改 |
| test | 测试用例相关修改 |
| ci | 持续集成修改 |
| revert | 版本回滚 |
| build | 编译相关的修改,例如对项目构建或者构建依赖的改动 |
| chore | 其他修改, 比如改变构建流程、或者增加依赖库、工具等 |
注: 如果执行创建commit-msg命令时不成功,可以先执行npx husky add .husky/commit-msg,会在.husky目录下生成一个commit-msg文件,然后将npx --no-install commitlint --edit $1复制到该文件中替换undefined。
在项目根目录创建commitlint.config.js文件
module.exports = {
extends: ['@commitlint/config-conventional']
}
@commitlint/config-conventional用来规定commit信息的提交规范。默认采用Angular规范
在package.json文件中添加lint-staged规则
"lint-staged": {
"**/*.{less,scss,sass}": [
"stylelint --fix",
"prettier --write ."
],
"**/*.{js?(x),ts?(x)}": [
"eslint . --fix",
"prettier --write ."
]
},
之后运行git commit时就会执行代码检查和commit信息的检查