2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue CLIプロジェクトでコンパイル時にコードフォーマットをかける

Last updated at Posted at 2020-05-29

前提

@vue/cli 4.4.1
vue create <projectName>

で作成したプロジェクト

  • Manually select features
  • Linter/Formatter にチェック
  • Pick a linter / formatter config > ESLint + Prettier
  • Pick additional lint features > Lint on save

lintエラーがある場合コンソールにメッセージが出るだけで
手動での修正が面倒なので、ファイル保存時に自動修正したいです。

ググればVScodeの設定でやる方法がわんさかあるのですが、
今回はエディターに依存したくなかったのでwebpack経由で自動修正をします。

なので、ファイル保存時ではなくコンパイル時ということになります。
また、どこからもimportされていないファイルや設定系ファイルなど、
webpackを通らないファイルに関しては自動修正されません。

設定方法

vue.config.js

Vue CLIでは vue.config.jsconfigureWebpackでwebpackの設定をマージできます。
Configuration Reference | Vue CLI

ということでプロジェクトルートに vue.config.js ファイルを作成して以下を記述。

vue.config.js
module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          enforce: 'pre',
          test: /\.(jsx?|tsx?|vue)$/,
          exclude: /node_modules/,
          loader: 'eslint-loader',
          options: {
            fix: true
          }
        }
      ]
    }
  }
}

.eslintrc.js

デフォルトのママ

.eslintrc.js
module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@vue/prettier/@typescript-eslint'
  ],
  parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  }
}

.prettierrc

プロジェクトルートに .prettierrc ファイルを作成してお好みの設定を記述

..prettierrc
{
  "semi": false,
  "arrowParens": "always",
  "singleQuote": true
}

おしまいける

以上で設定完了です。

保存前.vue
<script lang="ts">
// 略
  private hoge = "hoge";
// 略
</script>
保存後.vue
<script lang="ts">
// 略
  private hoge = 'hoge'
// 略
</script>

これでnpm run serveでサーバを立ち上げてる間、ファイル保存時に自動フォーマットが効いてくれます。
もちろん npm run serve, npm run build 実行時にも効きます。

冒頭にも記載した通りwebpackを経由しないファイルは修正されないので、
lintコマンドを活用しましょう

参考

Configuration Reference | Vue CLI

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?