LoginSignup
56
46

More than 5 years have passed since last update.

Nuxt.js で ESLint & Prettier を導入する

Posted at

ESLint だけでもコード整形はできるようですが、Prettier のコード整形の方が優れているらしい。
Nuxt.js の公式ドキュメントの通り、併用して導入することにします。

Nuxt.js で ESLint を使う

インストール

$ npm install --save-dev babel-eslint eslint eslint-config-prettier eslint-loader eslint-plugin-vue eslint-plugin-prettier prettier

ESLint の設定ファイルをつくる

プロジェクトの root に .eslintrc.js を作る

.eslintrc.js
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true
  },
  parserOptions: {
    parser: 'babel-eslint'
  },
  extends: [
    "eslint:recommended",
    // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
    // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
    "plugin:vue/recommended",
    "plugin:prettier/recommended"
  ],
  // required to lint *.vue files
  plugins: [
    'vue'
  ],
  // add your custom rules here
  rules: {
    "semi": [2, "never"],
    "no-console": "off",
    "vue/max-attributes-per-line": "off",
    "prettier/prettier": ["error", { "semi": false }]
  }
}

注意

公式ドキュメントをコピペすると module.exports { となっていましたが、
IDEに文法エラーだと怒られたので module.exports = { に修正しました。

package.json にエイリアスコマンドを追加する

package.json
"scripts": {
  "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
  "lintfix": "eslint --fix --ext .js,.vue --ignore-path .gitignore ."
}

以上で npm run lint で LINT チェック、 npm run lintfix で LINT の簡易修正が可能になる。
ちなみに、ESLint は .gitignore に書いてあるものは無視します。

ホットリローディングしたいとき

npm run dev 中は常に変更を検知させたい場合(というかそうするのがおすすめ)は nuxt.config.js で下記のような設定をする。

nuxt.config.js
  /*
   ** Build configuration
  */
  build: {
   /*
    ** You can extend webpack config here
   */
   extend(config, ctx) {
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: "pre",
          test: /\.(js|vue)$/,
          loader: "eslint-loader",
          exclude: /(node_modules)/
        })
      }
    }
  }

参考

公式ドキュメント
Step by Stepで始めるESLint
Prettier 入門 ~ESLintとの違いを理解して併用する~

56
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
46