前端编码规范

prettier 配置

1. vscode 安装prettier 的 插件

前端编码规范_第1张图片

2. 新建 .prettierrc 文件

{
  "semi": false, // 不尾随分号
  "singleQuote": true,  // 使用单引号
  "trailingComma": "none" // 多行逗号分隔的语法,最后一行不加逗号
}

eslint 配置

1. 创建.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: ['plugin:vue/vue3-essential', '@vue/standard'],
  parserOptions: {
    parser: '@babel/eslint-parser'
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
     // prettier 和 eslint的冲突,需要关闭当前规则校验(ex: created() { ...}.    这个created 和 ()中间没有空格报错导致的冲突)
    'space-before-function-paren': 'off'
  }
}

git 提交规范(npm > 7.x)

1. commitlint (检测提交信息)

    1. 安装
npm install --save-dev @commitlint/[email protected]  @commitlint/[email protected]
    1. 创建 commitlint.config.js
module.exports = {
  // 继承规格
  extends: ['@commitlint/config-conventional'],
  // utf-8
  roles: {
    // type 的类型定义: 表示git提交
    // type 必须在以下范围类
    'type-enum': [
      // 当前验证的错误级别
      2,
      // 什么情况下进行验证
      'always',
      // 范型内容
      [
        'feat', //  新功能
        'fix', // 修复 bug
        'docs', // 文档注释
        'style', // 代码格式 (不影响代码运行的变动)
        'refactor', // 重构(不增加新功能,也不修复bug)
        'perf', // 性能优化
        'test', // 测试
        'chore', // 构建过程或者辅助工具变动
        'revert', // 回退
        'build' // 打包
      ]
    ],
    // subject 大小写不做校验
    'subject-case': [0]
  }
}

2. husky (githook的工具)

    1. 安装依赖
npm install [email protected] - - save-dev
    1. 启动hooks,生成.husky 文件夹
npx husky install

前端编码规范_第2张图片

    1. 在package.json 中生成prepare指令(需要 npm ≥7.0 版本)
npm set-script prepare "husky install"

前端编码规范_第3张图片

    1. 执行 prepare 指令
npm run prepare
    1. 成功提示
      前端编码规范_第4张图片
    1. 添加commitlint 的hook 到husky中,并指令在commit-msg 的hooks下执行 npx --no-installcommitlint --edit "$1” 指令
npx husky add husky/commit-msg 'npx --no-install commitlint --edit "$1"'
    1. 文件结构

前端编码规范_第5张图片

    1. 测试
      前端编码规范_第6张图片

3. pre-commit 检测代码提交规范

    1. 执行 npx husky add .husky/pre-commit "npx eslint --ext .js,.vue src"添加commit 时的hook(npx eslint --ext . js,.vue sre 会在执行到该hook 时运行)
    1. 文件夹目录
      前端编码规范_第7张图片
    1. 自行测试, 不符合eslint规范的代码无法提交

缺点: pre-cormit 处理了 检测代码的提交规范向题,当我们进行代码提交时,会检测所有的代码格式规范。

4. lint-staged自动修复格式错误(无需安装,vue3内置了)

检测成功,直接提交代码,
检测不成功,自动修复然后提交代码
检测不成功,修复失败,手动修复在提交代码

    1. 修改package.json(新增代码)
  "gitHookst": {
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "src/**/*.{js,vue}": [
      "eslint --fix"
    ]
  }
    1. 修改 pre-commit

前端编码规范_第8张图片

你可能感兴趣的:(前端)