代码规范

ESLint 和 Prettier

介绍

ESLint

ESLint 是2013年出来的工具(在它之前有类似的,被淘汰了,好像是jslint)

项目中根目录的 .eslintrc (rc => rule config) 就是规则配置,并且是commonjs规范的

Vue-cli 中可以选择几个配置

module.exports = {
    root: true, // 哪个目录
    env: {node: true},
    extends: [], // 可以继承在哪些规则底下
    parseOptions: {parser: 'babel-eslint'},
    rules: {
        "no-console": "off" // off, warn, error 这三个value,也可以是0 1 2
    },
}

Prettier

这个是代码格式化的工具
也可以在vscode中配置autosave来达到自动格式化的要求

比如,在vscode中安装插件:

Prettier

然后在项目根目录添加一个 .prettierrc 的文件

{
    "semi": false,
    "singleQuote": true,
    "trailingComma": "all", // 对象的最后一项加逗号
}

保存自动格式化

在vscode的设置中
搜索save
勾选 format on save
就可以了

解决ESLint和Prettier中的冲突

在.rc 文件中添加冲突的规则

GIT提交规范

基本代码规范要求

commit message:

<type>[optional scope]: <description>

[optional body]

[optional footer]


Commitizen

使用

  1. 使用npm or yarn 全局安装
    npm install -g commitizen
  2. 在项目中安装
    npm install cz-customizable --S
  3. 在package.json中添加配置
"config": {
    "commitizen" : {
        "path": "node_modules/cx/customizable"
    }
}
  1. 创建配置文件 .cz-config.js 也是遵循commonjs
module.exports = {
    types: [ // 对应上面的type
        {
            value: 'feat', name: 'feat:    (这是我在脚手架中的提示)'
        },
        {
            value: 'chore', name: 'chore:     构建过程或日常的变动'
        },
        {
            value: 'refactor', name: 'refactor:      重构'
        }
    ],
    message: { // 提示信息
        type: '请选择提交的类型: ',
        customScope: '请输入范围 [optional]',
        subject: 'xxx',
        body: 'xxx'
        footer: 'xxx',
        confirmCommit: 'are u sure to use these message to commit?',
    },
    subjectLimit: 80, // 默认限制的长度
    skipQuestions: ['body', 'footer'] // 可以在输入阶段跳过这几个
}
  1. 使用 git cz 代替 git commit
    提交就OK了

husky + commitlint

Git Hooks

(npm 要在7版本以上,没有的话可以 npm install npm -g) 安装最新版本
Hooks 钩子,也就是git在操作的生命周期
比如,commit前,commit后,等等动作的回调

commitlint: 检查信息
husky: git hooks 的工具

commitlint安装:
npm install @commitlint/config-conventional @commitlint/cli -S

创建 commitlint.config.js 文件

module.exports = {
    extends: ['@commitlint/config-conventional'],
    rules: {
        'type-enum': [
            2, // 验证的级别 2 对应错误级别 (0 | off, 1 | warn, 2 | error)
            'always', // 在什么时候验证
            ['feat', 'fix', 'docs', 'style', 'chore', 'build', 'revert'] // type的内容
        ],
        'subject-case': [0], // 不对subject校验
    }
}

husky
安装:
npm install husky -S
启动:
npx husky install 会生成一个 .husky 的文件夹

然后新增一个script
npm set-script prepare "husky install"
也可以自己手动在package.json 的script下添加 prepare: husky install

运行指令
npm run prepare

husky 配合 commitlint 使用

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

添加一个commit-msg的文件在.husky 文件夹下面,并且添加这个文字

执行git commit -m "xxx"
提示失败了

husky配合eslint实现检测提交时的代码规范

使用husky 在 pre-commit 这个钩子下监测文件
命令
npx husky add .husky/pre-commit "npx eslint --ext .js,.vue,.jsx,.ts,.tsx src"

最后修改:2021 年 11 月 18 日 06 : 55 PM
如果觉得我的文章对你有用,请随意赞赏