项目代码规范集成
发布时间 2023-10-27 09:09:56

前言

  本篇文章的主要内容是:如何快速的为团队开发项目集成项目代码规范?

项目创建

1
2
3
npm install -g @vue/cli

vue create my-project
1
2
3
4
npm create vue@latest
# 或者
npm create vue@2
npm create vue@3
1
npm create vite@latest

一、代码规范集成

 在团队开发中,对于代码规范集成大致可以分为以下几个步骤:

1、ESLint

(1) ESLint + Prettier 方案

  使用 vue-cli 搭建 vue2 项目时,我们可以直接使用它集成的服务,甚至还可以让其自动 Git Hook(yorkie 方案)。

Linter / Formatter —> ESLint + Prettier —> Lint and fix on commit

  • .prettierrc / .prettierignore
内容如下:
  • .prettierrc
1
2
3
4
5
6
7
8
9
{
"useTabs": false, // 使用tab缩进还是空格缩进
"tabWidth": 2, // tab是空格的情况下,是几个空格

"trailingComma": "none", // 在多行输入的尾逗号是否添加(默认为all)
"semi": false, // 语句末尾是否要加分号(默认为true)
"singleQuote": true, // 使用单引号还是双引号(默认为false)
"printWidth": 100 // 当行字符的长度(默认80)
}
  • .prettierignore
1
2
3
4
5
6
7
8
9
/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*
  • .vscode 文件
内容如下:
  • extensions.json
1
2
3
{
"recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"]
}
  • settings.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
// Prettier
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",

// ESLint
"eslint.lintTask.enable": true,
"eslint.validate": ["javascript", "javascriptreact", "vue", "typescript", "typescriptreact"],

// 如果您使用 ESLint 作为默认格式化程序,则应在打开 editor.codeActionsOnSave 时关闭 editor.formatOnSave 。否则,您的文件将被修复两次,这是不必要的。
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}

(2) @antfu/eslint-config 方案

  具体可以查看 Anthony Fu 的博文为什么我不使用 Prettier

1
npx @antfu/eslint-config@latest

(2) eslint-config-alloy 方案

  eslint-config-alloy 是由腾讯 AlloyTeam 团队打造的,具体可以查看eslint-config-alloy

3、StyleLint

  -yorkie(如:vue2)支持在package.json中通过”xxxx”: {“pre-commit”: xxx}的方式更新脚本

  • 安装插件

vue 脚手架 vue-cli 在初始化完项目后,@vue/cli-service 会自动安装 yorkie

1
npm install stylelint stylelint-scss stylelint-config-standard -D
  • .stylelintrc.json
1
2
3
4
5
6
7
{
"extends": "stylelint-config-standard",
"plugins": ["stylelint-scss"],
"rules": {
// 在这里添加或覆盖任何 Stylelint 规则
}
}

二、Git Hooks 集成

说明

  Git Hooks 中的钩子会操作全局文件触发,所以我们通常会使用 lint-staged 来让 Git Hooks 只操作 Git 暂存区的内容。

lint-staged.config.json
1
2
3
4
5
6
7
8
{
"*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix"],
"{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": ["prettier --write--parser json"],
"package.json": ["prettier --write"],
"*.vue": ["prettier --write", "eslint --fix", "stylelint --fix"],
"*.{scss,less,styl,html}": ["prettier --write", "stylelint --fix"],
"*.md": ["prettier --write"]
}

1、yorkie 方案

  -yorkie(如:vue2)支持在package.json中通过”xxxx”: {“pre-commit”: xxx}的方式更新脚本

  • 安装插件

vue 脚手架 vue-cli 在初始化完项目后,@vue/cli-service 会自动安装 yorkie

1
npm install yorkie lint-staged chalk -D
具体集成步骤
  • package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"scripts": {
// ESLint
"lint": "vue-cli-service lint"
// Prettier
// "format": "prettier --write"
},

// yorkie
"gitHooks": {
"pre-commit": "npx lint-staged",
"commit-msg": "node scripts/verify-commit-msg.mjs"
},
// lint-staged(单独写在.lintstagedrc.json中)
"lint-staged": {
"*.{js,vue}": ["vue-cli-service lint", "stylelint --fix", "prettier --write"]
}
}
  • scripts / verify-commit-msg.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import chalk from 'chalk'
import { readFileSync } from 'fs'
import path from 'path'

const msgPath = path.resolve('.git/COMMIT_EDITMSG')
const msg = readFileSync(msgPath, 'utf-8').trim()

const commitRE =
/^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
console.log()
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
chalk.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
) +
` ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
` ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
chalk.red(` See .github/commit-convention.md for more details.\n`)
)
process.exit(1)
}

2、simple-git-hooks 方案

  -simple-git-hooks(如:vue3)支持在package.json中通过”simple-git-hooks”: {“pre-commit”: xxx}的方式更新脚本

  • 安装插件

simple-git-hooks 相较于 yorkie 配置更少,简单易用

1
npm install simple-git-hooks lint-staged chalk -D
具体集成步骤
  • package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"scripts": {
// ESLint
"lint": "vue-cli-service lint"
// Prettier
// "format": "prettier --write"
},

// simple-git-hooks
"simple-git-hooks": {
"pre-commit": "npx lint-staged",
"commit-msg": "node scripts/verify-commit-msg.mjs"
},
// lint-staged(单独写在.lintstagedrc.json中)
"lint-staged": {
"*.{js,vue}": ["vue-cli-service lint", "stylelint --fix", "prettier --write"]
}
}
  • scripts / verify-commit-msg.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import chalk from 'chalk'
import { readFileSync } from 'fs'
import path from 'path'

const msgPath = path.resolve('.git/COMMIT_EDITMSG')
const msg = readFileSync(msgPath, 'utf-8').trim()

const commitRE =
/^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
console.log()
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
chalk.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
) +
` ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
` ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
chalk.red(` See .github/commit-convention.md for more details.\n`)
)
process.exit(1)
}

3、husky 方案

  husky(如:vue-vben-admin支持修改.husky/xxx目录下的配置脚本

  • 安装插件
1
2
3
4
npm install husky lint-staged chalk -D

# 初始化 husky
npx husky init
具体集成步骤
  • .husky / pre-commit
1
2
3
. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged
  • .husky / pre-commit
1
2
3
. "$(dirname -- "$0")/_/husky.sh"

node scripts/verify-commit-msg.js
  • package.json
1
2
3
4
5
6
{
// lint-staged(单独写在.lintstagedrc.json中)
"lint-staged": {
"*.{js,vue}": ["vue-cli-service lint", "stylelint --fix", "prettier --write"]
}
}
  • scripts / verify-commit-msg.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import chalk from 'chalk'
import { readFileSync } from 'fs'
import path from 'path'

const msgPath = path.resolve('.git/COMMIT_EDITMSG')
const msg = readFileSync(msgPath, 'utf-8').trim()

const commitRE =
/^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
console.log()
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
chalk.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
) +
` ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
` ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
chalk.red(` See .github/commit-convention.md for more details.\n`)
)
process.exit(1)
}
拓展:卸载 husky
1
2
3
4
npm uninstall husky && git config --unset core.hooksPath # husky官方给的命令

git config core.hooksPath .git/hooks/ # simple-git-hooks官方给的命令
rm -rf .git/hooks

三、Commit 规范

  什么是 commit 规范就不多说了,现在比较认可的就是Angular的那套规范。

1、脚本文件

  这个方案是我比较喜欢的,也是上面我编写的示例中就是采用的方案。因为他不需要下载任何包,非常轻量级。

verify-commit-msg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// @ts-check
import chalk from 'chalk'
import { readFileSync } from 'fs'
import path from 'path'

const msgPath = path.resolve('.git/COMMIT_EDITMSG')
const msg = readFileSync(msgPath, 'utf-8').trim()

const commitRE =
/^(revert: )?(feat|fix|docs|dx|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
console.log()
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
chalk.red(
` Proper commit message format is required for automated changelog generation. Examples:\n\n`
) +
` ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
` ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
chalk.red(` See .github/commit-convention.md for more details.\n`)
)
process.exit(1)
}

2、commitizen

  这种方案我只能说是优缺点并存。优点是:commitizen对 commit 信息的约束非常严谨,并且可以快速生成更新日志;缺点是:要求我们使用 git cz 命令来代替 git commit 命令,并且为了防止我们使用 git commit 还要额外的安装 commitlint,显然这是反用户习惯的。

cz-conventional-changelog

  • 安装插件
1
2
# cz-conventional-changelog 为适配器
npm install commitizen cz-conventional-changelog -D
  • 项目集成

可以通过 npm run commit 或 git cz 使用

1
2
3
4
5
6
7
8
9
10
11
// package.json
{
"scripts": {
"commit": "git-cz"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}
  • 防止 git commit
1
2
3
4
5
6
# 安装
npm install --save-dev @commitlint/config-conventional @commitlint/cli

# 配置
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"

3、czg ✨

  这个是我在vue-vben-admin)中看到的一个方案。

czg 可以理解为是一款内置了 cz-git 适配器的 Commitizen CLI 替代品,它更加轻量。

cz-git 适配器

1
npm install czg cz-git -D
  • 项目集成

可以通过 npm run commit 或 git cz 使用

1
2
3
4
5
6
7
8
9
10
11
// package.json
{
"scripts": {
"commit": "czg"
},
"config": {
"commitizen": {
"path": "node_modules/cz-git"
}
}
}
上一页
2024-06-11 00:39:23
下一页