長野エンジニアライフ

東京から長野に移住したエンジニアのブログです。🦒🗻⛰

Vueプロジェクトにeslintを導入

[:contens]

eslint関連のパッケージをインポート

package.jsonに以下を追加

{
...
    "husky": "^4.2.5",
    "lint-staged": "^10.2.2",
...
    "eslint-config-standard": "^14.1.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-node": "^10.0.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "vue-eslint-parser": "^6.0.4"
...
}

.eslintrc.jsの作成

$ touch .eslintrc.js
module.exports = {
    root: true,
    parser: 'vue-eslint-parser',
    parserOptions: {
        ecmaVersion: 2018,
        parser: 'babel-eslint',
        sourceType: 'module'
    },
    extends: ['standard'],
    plugins: [
        'vue'
    ],
    rules: {
        'vue/html-indent': ['error', 2] // 2 spaces for html indent
    }
}

eslintの実行

nodeのバージョンを10.移行にしないと動かないのであげた

$ nodebrew use v12.10.0
$ npm run lint

色いろエラーを吐いてくれた

///
   1:22  error  Extra semicolon                                semi
   2:35  error  Extra semicolon                                semi
   3:47  error  Extra semicolon                                semi
   5:19  error  Extra semicolon                                semi
   8:1   error  Expected indentation of 2 spaces but found 4   indent
   8:40  error  Unexpected trailing comma                      comma-dangle
   9:2   error  Extra semicolon                                semi
  12:1   error  Expected indentation of 2 spaces but found 4   indent
  13:1   error  Expected indentation of 2 spaces but found 4   indent
  14:3   error  Extra semicolon                                semi
  16:22  error  Extra semicolon                                semi
  16:23  error  Newline required at end of file but not found  eol-last

✖ 17 problems (17 errors, 0 warnings)
  17 errors and 0 warnings potentially fixable with the `--fix` option.

コミット時にルール通りに修正するようにする

package.jsonを修正

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "eslint --ext .js,.vue src --config .eslintrc.js --fix"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,vue}": [
      "eslint --fix",
      "git add"
    ]
  },

コミット時に自動で修正してくれた。

参考記事

qiita.com kic-yuuki.hatenablog.com