使用eslint和githooks統一前端風格

使用eslint和githooks統一前端風格

前端團隊開發時,是必需要有一個統一的前端規範的,用一套統一的規範來規範開發者,能夠有效的避免在提交和拉取代碼時形成的代碼錯亂問題,這邊文章主要講下咱們團隊的代碼規範使用,eslint結合vscode保存時自動修復不規範代碼,githooks提交代碼時的eslint校驗和信息規範。

添加eslint

vue-cli3構建一個新項目(包含eslint模塊),完成後添加.eslintrc.js配置以下:javascript

module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint',
    sourceType: 'module'
  },
  env: {
    browser: true
  },
  // https://github.com/standard/standard/blob/master/docs/RULES-en.md
  extends: [
    'plugin:vue/base'
  ],
  // required to lint *.vue files
  plugins: [
    'vue'
  ],
  // add your custom rules here
  'rules': {
    // allow paren-less arrow functions
    'indent': [2, 2], // 兩個空格的縮進
    'quotes': [2, 'single'], // js必須使用單引號
    'linebreak-style': [2, 'unix'], // 換行風格 unix/windows
    'semi': [2, 'never'], // 語句強制分號結尾
    // 'no-console': [1], // 不容許console語句
    'no-unused-vars': [1], // 聲明瞭變量可是沒有使用檢測
    'space-unary-ops': [1, { 'words': true, 'nonwords': false }], // 一元運算符的前/後要不要加空格
    'brace-style': [2, '1tbs', { 'allowSingleLine': false }], // 大括號風格
    'comma-spacing': [2, { 'before': false, 'after': true }],   // 逗號後有空格,前沒有空格
    'comma-style': [2, 'last'],  // 逗號跟在結尾
    'key-spacing': [2, { 'beforeColon': false, 'afterColon': true }], // 對象字面量中冒號的先後空格
    'lines-around-comment': [ // 行前/行後備注
      2, {
        'beforeBlockComment': false, // 段註釋的先後
        'beforeLineComment': false, // 行註釋的前面
        'afterBlockComment': false, // 塊註釋的後面
        'afterLineComment': false, // 行註釋的後面
        'allowBlockStart': true,
        'allowObjectStart': true,
        'allowArrayStart': true
      }],
    'max-depth': [2, 4], // 代碼最多容許4層嵌套
    'max-len': [1, 1000, 2],
    'max-nested-callbacks': [2, 3], // 回調嵌套深度
    'max-params': [2, 5], // 函數最多隻能有5個參數
    'max-statements': [1, 80],  // 單個函數最多80條語句
    'no-array-constructor': [2], // 禁止使用數組構造器
    'no-lonely-if': 2, // // 禁止else語句內只有if語句
    'no-multiple-empty-lines': [2, { 'max': 3, 'maxEOF': 1 }], // 空行最多不能超過2行
    'no-nested-ternary': 2,  // 不使用嵌套的三元表達式
    'no-spaced-func': 2, // 函數調用時 函數名與()之間不能有空格
    'no-trailing-spaces': 2, // 一行結束後面不要有空格
    'no-unneeded-ternary': 2, // 禁止沒必要要的嵌套 var isYes = answer === 1 ? true : false;簡單的判斷用三元表達式代替
    'object-curly-spacing': [2, 'always', { // 大括號內是否容許沒必要要的空格 always始終容許;never始終不容許
      'objectsInObjects': false,
      'arraysInObjects': false
    }],
    'arrow-spacing': 2, // =>的前/後括號
    'block-scoped-var': 2, // 塊語句中使用var
    'no-dupe-class-members': 2,
    // 'no-var': 1, // 禁用var,用let和const代替
    'object-shorthand': [1, 'always'], // 強制對象字面量縮寫語法
    'array-bracket-spacing': [2, 'never'], // 是否容許非空數組裏面有多餘的空格
    'operator-linebreak': [2, 'after'], // 換行時運算符在行尾仍是行首
    // 'semi-spacing': [2, { 'before': false, 'after': false }], // 分號先後空格
    'keyword-spacing': ['error'],
    'space-before-blocks': 2, // 不以新行開始的塊{前面要不要有空格
    'block-spacing': [2, 'always'],
    'space-before-function-paren': [2, 'never'], // 函數定義時括號前面要不要有空格
    'space-in-parens': [2, 'never'], // 小括號裏面要不要有空格
    'spaced-comment': [1, 'always',
      {
        'exceptions': ['-', '*', '+']
      }], // 註釋風格要不要有空格什麼的
    'arrow-parens': 0,
    // allow async-await
    'generator-star-spacing': 0,
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
  },
  globals: {
    '$': false,
    'jquery': false,
    'ActiveXObject': false,
    'arbor': true,
    'layer': false
  }
}

運行npm run lint會給出報錯,運行npm run serve也會對項目進行eslint校驗,沒法經過校驗就會報錯
error.jpghtml

能夠結合vscode的eslint插件快速修復沒法經過驗證的代碼,首先下載插件,而後更改setting.json配置文件,具體以下:前端

"eslint.validate": [
    "javascript",
    "javascriptreact",
    "vue-html"
],
"eslint.run": "onSave",
"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
}

配置完成以後重啓vscode,在編輯代碼的時候若是未符合eslint的校驗,保存時會自動修復代碼。vue

添加git hooks

前端團隊開發中若是沒有作正確的校驗就提交了代碼,拉取代碼時會致使不少地方爆紅不符合定製的開發規範,所以能夠在提交代碼時作些限制.在git提交代碼時,會觸發一些列的鉤子函數,能夠經過husky這個git hooks的工具來進行代碼提交校驗,須要先安裝依賴包cnpm i -D husky lint-staged @commitlint/config-conventional @commitlint/cli.而後在package.json中添加以下代碼:java

// package.json
"husky": {
  "hooks": {
    "pre-commit": "lint-staged",// 在pre-commit階段運行下面配置的校驗功能
    "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" // 這個是規範提交的信息的,結合commitlint.config.js使用
  }
},
"lint-staged": {
  "src/**/*.{js,vue}": [
    "npm run lint",
    "git add ."
  ]
}
// commitlint.config.js
// 參考的官方配置,提交的信息必須按照下面規範書寫,相似`git commit -m 'feat: 添加eslint'`
module.exports = {
  parserPreset: 'conventional-changelog-conventionalcommits',
  rules: {
    'body-leading-blank': [1, 'always'],
    'body-max-line-length': [2, 'always', 100],
    'footer-leading-blank': [1, 'always'],
    'footer-max-line-length': [2, 'always', 100],
    'header-max-length': [2, 'always', 100],
    'scope-case': [2, 'always', 'lower-case'],
    'subject-case': [
      2,
      'never',
      ['sentence-case', 'start-case', 'pascal-case', 'upper-case']
    ],
    'subject-empty': [2, 'never'],
    'subject-full-stop': [2, 'never', '.'],
    'type-case': [2, 'always', 'lower-case'],
    'type-empty': [2, 'never'],
    'type-enum': [
      2,
      'always',
      [
        'build',
        'chore',
        'ci',
        'docs',
        'feat',
        'fix',
        'perf',
        'refactor',
        'revert',
        'style',
        'test'
      ]
    ]
  }
}

接下來修改文件提交代碼,最後commit的時候就會對已修改文件進行校驗,若是eslint校驗不經過,或者commit信息不符合規範都是不能提交代碼的,以上步驟已經能夠很好的改善代碼和提交信息規範,這對於團隊項目開發可以很大對提升代碼質量。react

相關文章
相關標籤/搜索