ESLintとは
JavaScriptプロジェクト開発において、ESLintは必ずと言っていいほど登場するツールです。ESLintはどのような役割を果たし、プロジェクトに何をもたらすのでしょうか?ESLintは、構文エラーや事前に定義されたルールに準拠したコードかどうかをチェックするツールです。ESLintは、開発者がコード内の潜在的な問題を発見するのを助けてくれます。Vueプロジェクトでは、ESLintは他の構文チェックツールと組み合わせて使用されることが一般的で、最も古典的な組み合わせはESLintとPrettierです。
ESLintとPrettierはVue.jsに限定されたものではなく、JavaScriptを学ぶ上で必須の知識です。そのため、ESLintに詳しくない方はぜひマスターしておきましょう。この記事を読んでも、ESLintとPrettierのすべてのルールを理解することは難しいかもしれませんが、実際の実行を通じて、ESLintとPrettierが何をするのかを完全に理解できるでしょう。以下では、テキストでの説明ではなく、実際のチェック操作を通じて、ESLintの機能と使い方を分かりやすく理解していきましょう。
1. ESLintのセットアップ
VueプロジェクトにESLintを導入する方法を見ていきましょう。ESLintの公式サイトはhttps://eslint.org/docs/latest/です。
- まず、ESLintをインストールします。
npm install eslint --save-dev
# Vueプロジェクト用のeslintプラグインをインストール
npm install eslint-plugin-vue --save-dev
- 次に、ESLintの設定ファイルを初期化します。
npm init @eslint/config
# または
npx eslint --init
上記のコマンドを実行すると、対話形式の質問が表示されます。
? How would you like to use ESLint? ...
To check syntax only //構文のみをチェック
> To check syntax and find problems //構文をチェックし問題を見つける
To check syntax, find problems, and enforce code style //構文をチェックし、問題を見つけ、コードスタイルを強制する
//コード品質の要件が高くないプロジェクトでは1番と2番を選択できます
//「構文をチェックし問題を見つける」を選択します。なぜなら、後でPrettierを使用してコードスタイルを強制するからです。
? What type of modules does your project use? ...
> JavaScript modules (import/export)
CommonJS (require/exports)
None of these
//JavaScriptモジュールを選択します。主な理由はVue3がそれ們を使用しているためです。
? Which framework does your project use? ...
React
> Vue.js
None of these
//Vueプロジェクトを選択します
//TypeScriptの構文を検証するかどうかを選択します
? Does your project use TypeScript? » No / Yes
//プロジェクトでTypeScriptを使用していないため、Noを選択します
//コードがどこで実行されるか
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
√ Node
//「Browser」を選択します。なぜなら、Vueプロジェクトはブラウザ上で実行されるWebプロジェクトだからです。もしデスクトップアプリやモバイルアプリであればNodeを選択します。
//設定ファイルの形式は何にしますか?
? What format do you want your config file to be in? …
JavaScript
YAML
▸ JSON
//開発中は通常、JavaScriptとJSONを.eslintrcファイル形式として使用します。
eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
//今すぐnpmでインストールしますか? Yesを選択します
? Which package manager do you want to use? ...
> npm
yarn
pnpm
実行が完了すると、プロジェクトに新しい .eslintrc.cjs ファイルが作成されます。
プロジェクト
|---node_modules
|---src
|---.eslintrc.cjs ESLint設定ファイル
|---package.json プロジェクト設定ファイル
|---vite.config.js vite設定ファイル
次に、プロジェクトの package.json ファイルに以下のスクリプトを追加します。
"scripts": {
"lint": "eslint --ext .js,.vue src"
}
最後に、ターミナルで npm run lint コマンドを実行してコードをチェックできます。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
ESLintの初期化が成功すると、プロジェクトに .eslintrc.js ファイルが作成されます。ファイルの内容は以下のようになります。
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential"
],
"overrides": [
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
}
}
package.json ファイルで、eslintとeslint-plugin-vueのインストールされたルールのバージョンを確認できます。
{
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"eslint": "^8.32.0",
"eslint-plugin-vue": "^9.9.0",
"vite": "^4.0.0"
}
}
2. ESLintルールの設定
プロジェクトのルートディレクトリにある .eslintrc.cjs ファイルの extends プロパティには、プロジェクトで使用するルールセットが定義されています。今後、ESLintに関連する他のルールセットも extends に追加する必要があります。後で触れるPrettierも extends で設定します。 extends で導入されたルールセットのみが、ESLintのチェックで使用されます。
- eslint:recommended はESLintの標準ルールです。
- plugin:vue/vue3-essential はVueの構文テンプレートルールです。
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential"
],
「eslint:recommended」が適用する検証ルールの内容は、ESLintのドキュメントで確認できます。
Vueの検証ルールの内容は、eslint-plugin-vueの公式サイトで確認できます。
ルールの有効性を検証するために、App.vueファイルのコードを変更します。
<script setup>
import SampleComponent from './components/SampleComponent.vue'
let testVariable = "テスト用の変数";
</script>
<template>
</template>
<style scoped>
</style>
lint構文チェック機能を実行すると、エディタはいくつかの構文ルールのエラーメッセージを表示します。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:8 error 'SampleComponent' is defined but never used no-unused-vars
3:5 error 'testVariable' is assigned a value but never used no-unused-vars
5:1 error The template requires child element vue/valid-template-root
✖ 3 problems (3 errors, 0 warnings)
上記の最初の2つのエラーは、ESLintルールによって検出された「no-unused-vars」のエラーです。ESLintルールとVueルールは異なります。先頭に「vue/」がないエラーは、ESLintの標準ルールのエラーです。 vue/valid-template-root は、eslint-plugin-vueによって検出されたVueの構文エラーのルール提示です。
「no-unused-vars」のエラーメッセージの詳細は、ESLintの公式サイトで確認できます。未使用の変数が定義されていないことに関するエラーです。
vue/valid-template-rootのルール情報は、eslint.vuejsの公式サイトで確認できます。エラーメッセージは、テンプレートにコンテンツがないことを示しています。
3. ESLint検証の設定
.eslintrc.js ファイルの rules プロパティは、ESLintの検証設定を行う場所です。 rules 内のプロパティを設定することで、ESLintの検証内容全体を制御できます。たとえば、競合するルールを無効にしたり、使用したくないルールを無効にしたり、インデント形式などを設定したりできます。ここでは、上記で発生したエラー提示の vue/valid-template-root ルールを無効にします。 .eslintrc.js ファイルの rules プロパティを編集し、rules プロパティに vue/valid-template-root を追加し、その値を off に設定します。 off はエラーレベルを示し、検証を無効にすることを意味します。
module.exports = {
......
"plugins": [
"vue"
],
"rules": {
//vue/valid-template-rootルールを無効にする
'vue/valid-template-root':'off'
}
}
設定が完了したら、再度 npm run lint コマンドを実行します。コンパイルが成功すると、エラー提示の vue/valid-template-root 情報が消えていることがわかります。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:8 error 'SampleComponent' is defined but never used no-unused-vars
3:5 error 'testVariable' is assigned a value but never used no-unused-vars
エラーレベルは「off」の他に、「warn」(警告)と「error」(エラー)があります。これらはルールの設定値です。 error に設定するとコンパイルが失敗します。 warn に設定すると、警告メッセージが表示されますが、コンパイルは正常に実行されます。開発とデバッグの便利さのために、プロジェクトの console と debugger のエラーを無効にし、プロジェクトのリリースとパッケージング時にこの検証を再度有効にすることができます。
rules: {
'vue/valid-template-root':'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
},
4. ESLintによるフォーマット設定
ESLintはフォーマッター(コードフォーマッター)としても使用できます。そのため、その設定方法もチェックします。フォーマッターを使用することで、インデントを設定し、プロジェクト全体のファイルでクォートやセミコロンが一貫しているかどうかを統一できます。
ESLintルールを使用して、インデントを2から4に変更します。フォーマッターの設定も .eslintrc.js ファイルに書くことができます。設定は配列で行われ、最初の要素でエラーレベルを設定し、2番目の要素で設定値を設定します。
module.exports = {
......
"plugins": [
"vue"
],
"rules": {
'vue/valid-template-root':'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
//フォーマット検証:インデントを4スペースにする
'indent': ['error', 4]
}
}
ここでインデント設定をチェックします。 App.vue ファイルを見ると、現在のインデントは2です。
<script setup>
let testVariable = "テスト用の変数";
const handleClick = () => {
//現在のインデントは2スペース
alert(1);
}
</script>
<template>
<div @click="handleClick">インデントは2スペース</div>
</template>
<style scoped>
</style>
lint構文チェックコマンドを実行すると、エディタはコンパイルエラーを表示します。5-1行目はエラーです。なぜなら、2スペースしかインデントされておらず、正しいインデントは4スペースだからです。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
5:1 error Expected indentation of 4 spaces but found 2 indent
Vueテンプレートのフォーマット設定
このとき、App.vueのコードのルール検証が、scriptタグ内のコードのインデント4スペースルールのみを検証し、templateタグ内のHTMLインデントは検証していないことに気づくでしょう。テンプレート内のHTMLインデントを検証するには、.eslintrc.jsファイルでテンプレートの検証項目を設定し、vue/html-indentルールを追加してテンプレートタグのインデントを検証する必要があります。
module.exports = {
......
"plugins": [
"vue"
],
"rules": {
'vue/valid-template-root':'off',
'indent': ['error', 4],
//テンプレートフォーマット設定
"vue/html-indent": ["error", 4]
}
}
lint構文チェックコマンドを実行すると、templateタグ内のHTMLインデントに関するエラー提示が表示されます。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
5:1 error Expected indentation of 4 spaces but found 2 indent
9:1 error Expected indentation of 4 spaces but found 0 spaces vue/html-indent
9-1行目は、4スペースインデントされていないことを示すエラーメッセージです。
5. ESLintによる自動修正
コードでインデントを4スペースに修正することもできますが、コード量が膨大な場合は、これは困難な作業になります。ESLintコマンドには、エラーを自動修正する機能が提供されており、この問題を簡単に解決できます。 npm run lint の後に -- --fix パラメータを追加します。
npm run lint -- --fix
コマンドを実行して、プロジェクト内のすべてのコードを検証し、修正します。
npm run lint -- --fix
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src "--fix"
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
App.vueのコードのインデント数がすべて4スペースに変更されました。
<script setup>
let testVariable = "テスト用の変数";
const handleClick = () => {
//現在のインデントは2スペース
alert(1);
}
</script>
<template>
<div @click="handleClick">インデントは2スペース</div>
</template>
<style scoped>
</style>
6. Prettierとの連携
Prettierは非常に強力なコードフォーマッターです。ESLintやTSLintなどのフォーマッターとは異なり、Prettierはコードのフォーマットの問題のみを検証し、構文の問題には関与しません。そのため、プロジェクトではESLintを単独で使用してコードの品質をチェックできます。しかし、ESLintは構文を専門に分析するため、一部のコード部分をカバーできない場合があります。このとき、Prettierを使用してコードのフォーマットをチェックする必要があります。
npm install prettier --save-dev
npm install @vue/eslint-config-prettier eslint-plugin-prettier --save-dev
- prettier: Prettierによるフォーマット。
- eslint-config-prettier: PrettierがカバーできるすべてのESLintルールを無効にする設定を提供し、ESLintとPrettierの競合を解決します。
- @vue/eslint-config-prettier: Vueプロジェクト用で、Prettierの機能がVueプロジェクトで正常に動作するように、Prettierと競合するすべてのESLintルールを無効にします。
package.json ファイルで、「@vue/eslint-config-prettier」、「eslint-plugin-prettier」、「prettier」の3つのパッケージが新しく追加されていることが確認できます。
{
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"@vue/eslint-config-prettier": "^7.0.0",
"eslint": "^8.33.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-vue": "^9.9.0",
"prettier": "^2.8.3",
"vite": "^4.0.0"
}
}
ESLintの設定ファイル .eslintrc.cjs の extends プロパティに「@vue/prettier」フォーマッターを追加します。
module.exports = {
......
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential",
"@vue/prettier"
],
}
検証コマンドを実行すると、prettierがコード内のすべてのフォーマットエラーを検出します。たとえば、コードの末尾の「;」セミコロン、二重引用符を単一引用符に変更する提示、コードのインデントが不規則な問題などです。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
2:8 warning Replace `="テスト用の変数"` with `·=·"テスト用の変数";` prettier/prettier
3:13 warning Replace `=()=>` with `·=·()·=>·` prettier/prettier
4:1 warning Replace `//現在のインデントは2スペース····` with `··//現在のインデントは2スペース` prettier/prettier
5:1 error Expected indentation of 4 spaces but found 2 indent
6:2 warning Insert `;` prettier/prettier
11:15 warning Delete `⏎` prettier/prettier
D:\vue\vue-project\src\main.js
1:27 warning Replace `'vue'` with `"vue";` prettier/prettier
2:8 warning Replace `'./style.css'` with `"./style.css";` prettier/prettier
3:17 warning Replace `'./App.vue'` with `"./App.vue";` prettier/prettier
5:22 warning Replace `'#app')` with `"#app");` prettier/prettier
✖ 15 problems (3 errors, 12 warnings)
1 error and 12 warnings potentially fixable with the `--fix` option.
自動修正コマンドを実行すると、Prettierも同じことを行います。Prettierはデフォルトのルールに基づいて、手動でコードを修正する必要なく、Vueプロジェクトのコードを自動的に修正します。
npm run lint -- --fix
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src "--fix"
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
4:3 warning Delete `··` prettier/prettier
5:1 error Expected indentation of 4 spaces but found 2 indent
✖ 4 problems (3 errors, 1 warning)
1 error and 1 warning potentially fixable with the `--fix` option.
App.vueのコードフォーマットが規則に合致し、手動でコードを調整する必要がなくなったことがわかります。
<script setup>
let testVariable = "テスト用の変数";
const handleClick = () => {
//現在のインデントは2スペース
alert(1);
};
</script>
<template>
<div @click="handleClick">インデントは2スペース</div>
</template>
<style scoped></style>
1. .prettierrcファイルの設定
VueプロジェクトのインストールフォルダにPrettierの設定ファイル .prettierrc を作成します。 .prettierrc ファイルはPrettierの設定ファイルで、改行文字、デフォルトのインデント(2)、行末のセミコロン、二重引用符などのフォーマットを設定するために使用されます。 .prettierrc ファイルでは、プロジェクトの実際の状況に基づいて、独自の検証ルールを定義します。
プロジェクト
|---node_modules
|---src
|---.eslintrc.cjs ESLint設定ファイル
|---.prettierrc Prettier設定ファイル
|---package.json プロジェクト設定ファイル
|---vite.config.js vite設定ファイル
.prettierrc ファイルに以下の設定を記述します。
{
"tabWidth": 4, //インデントの幅
"semi": false, //コードの末尾にセミコロンを使用しない
"singleQuote": true //二重引用符ではなく単一引用符を使用する
}
すべての検証フォーマットの説明は、公式サイトのhttps://prettier.io/docs/en/options.htmlで確認できます。
npm run lintを実行して、コードフォーマットのエラー提示を確認します。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
2:11 warning Replace `"テスト用の変数";` with `'テスト用の変数'` prettier/prettier
4:1 warning Replace `··` with `····` prettier/prettier
4:1 error Expected indentation of 4 spaces but found 2 indent
5:1 warning Replace `··alert(1);` with `····alert(1)` prettier/prettier
5:1 error Expected indentation of 4 spaces but found 2 indent
9:1 warning Insert `··` prettier/prettier
✖ 8 problems (4 errors, 4 warnings)
2 errors and 4 warnings potentially fixable with the `--fix` option.
同様に、npm run lint – --fixコマンドを使用してコードフォーマットルールを自動修正できます。
npm run lint -- --fix
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src "--fix"
D:\vue\vue-project\src\App.vue
2:5 error 'testVariable' is assigned a value but never used no-unused-vars
✖ 2 problems (2 errors, 0 warnings)
App.vueのコードが変更され、フォーマットエラーが修正されました。コードのセミコロンが消え、二重引用符が単一引用符になり、インデントが4スペースになりました。
<script setup>
let testVariable = 'テスト用の変数'
const handleClick = () => {
//現在のインデントは2スペース
alert(1)
}
</script>
<template>
<div @click="handleClick">インデントは2スペース</div>
</template>
<style scoped></style>
2. .eslintrc.cjsでのPrettier設定
.eslintrc.cjs ファイルで、.prettierrc の同じ機能を設定できます。これにより、プロジェクトで .prettierrc 設定ファイルを使用してフォーマット検証ルールを設定する必要がなくなり、プロジェクトをよりクリーンに保つことができます。
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential",
"@vue/prettier"
],
"overrides": [
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
'vue/valid-template-root':'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
//prettier検証設定
"prettier/prettier": [
"error",
{
tabWidth: 2,
singleQuote: false,
semi: true,
},
],
}
}
7. Babelとの統合
BabelはJavaScriptコードコンパイラで、ES6、ES7、ES8などのコードをES5コードに変換できます。より分かりやすく言うと、Nodeの構文コードをブラウザで実行できるJavaScriptコードに変換することです。BabelはESLintと組み合わせて、Vueプロジェクトのコード品質検証を行うことができます。Babelはコードの変換作業を担当し、ESLintはコードの構文エラーのチェックと修正を行います。
これら2つを組み合わせることで、コードの静的解析と検証を実現し、潜在的な問題やリスクポイントを特定できます。サーバーを起動せずに、Nodeの構文コード、CSSスタイル、HTMLテンプレートスタイルを検証し、プロジェクト全体のコードに潜在的な問題を検出できます。BabelとESLintをプロジェクトに統合するには、多种類の@babelコンポーネントを導入する必要があります。公式サイトで使用するコンパイラの対応するタイプのコンポーネントを見つけることができます。プロジェクトのバージョンが低い場合は、babel-eslintコンポーネントを使用できます。Babelの公式サイトはhttps://babeljs.io/です。
- プロジェクトにBabelの依存コンポーネントをインストールします。
npm install @babel/core @babel/eslint-parser --save-dev
npm install @babel/preset-env --save-dev
npm install @babel/preset-react --save-dev
.eslintrc.cjsファイルでBabel情報を設定します。parserOptionsプロパティで"parser": '@babel/eslint-parser'を設定し、他の設定オプションもparserOptionsプロパティで設定できます。
- requireConfigFile false: Babel設定ファイルがない場合でも、@babel/eslint-parserが実行できるようにします。
- babelOptions: Babel解析の設定オブジェクトで、設定ファイルのBabel基本設定項目の代わりになります。
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential",
"@vue/prettier"
],
"overrides": [
],
//vue-eslint-parser
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
//設定ファイルなしモード
"requireConfigFile": false,
//ESLintにBabelプラグインを統合
"parser": '@babel/eslint-parser',
//Babel設定情報の設定
"babelOptions": {
babelrc: false,
configFile: false,
//Babelが使用するコンパイラタイプ
presets: ["@babel/preset-env"],
"parserOpts": {
"plugins": ["jsx"]
}
}
},
"plugins": [
"vue"
],
"rules": {
}
}
App.vueファイルのコード内容を使用して、ESLint+PrettierとBabelによる品質検証を行います。
<script setup>
const testMessage = 'テスト用のメッセージ'
const handleSearch = ()=> {
// 現在のインデントは2スペース
alert(1)
}
</script>
<template>
<div @click="handleSearch">インデントは2スペース</div>
</template>
<style scoped>
npm run lintコマンドを実行してBabelの設定が成功したか検証します。バックエンドに異常がないこと、構文エラーの提示があることから、Babelコンポーネントの統合が成功したことを示します。
npm run lint
> vue-project@0.0.0 lint
> eslint --ext .js,.vue src
D:\vue\vue-project\src\App.vue
2:7 error 'testMessage' is assigned a value but never used no-unused-vars
2:10 warning Replace `='テスト用のメッセージ'` with `·=·"テスト用のメッセージ";` prettier/prettier
3:15 warning Replace `()` with `·()·` prettier/prettier
4:1 warning Insert `··` prettier/prettier
5:1 warning Replace `alert(1)` with `··alert(1);` prettier/prettier
6:2 warning Insert `;` prettier/prettier
9:1 warning Insert `··` prettier/prettier
12:5 warning Insert `·` prettier/prettier
13:1 warning Replace `font-size:` with `··font-size:·` prettier/prettier
D:\vue\vue-project\src\components\SampleComponent.vue
2:10 error 'ref' is defined but never used no-unused-vars
2:21 warning Replace `'vue'` with `"vue";` prettier/prettier
5:1 error The template requires child element vue/valid-template-root
D:\vue\vue-project\src\main.js
1:27 warning Replace `'vue'` with `"vue";` prettier/prettier
2:8 warning Replace `'./style.css'` with `"./style.css";` prettier/prettier
3:17 warning Replace `'./App.vue'` with `"./App.vue";` prettier/prettier
5:22 warning Replace `'#app')` with `"#app");` prettier/prettier
✖ 16 problems (3 errors, 13 warnings)
Babel設定ファイルを使用してBabel機能を設定する場合は、.eslintrc.cjsファイルの requireConfigFile プロパティを削除する必要があります。プロジェクトのルートディレクトリに .babelrc ファイルを作成し、.babelrc ファイルでBabel機能を設定します。
.babelrc ファイルで @babel/preset-env コンポーネントの内容を設定します。.babelrc ファイルのパラメータ属性は、公式サイトで確認できます。
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"ie": 11,
"esmodules": true
},
"useBuiltIns": "usage",
"corejs": 3
}
]
]
}
BabelはJavaScript、CSS、HTML、TypeScript、その他のテンプレート言語を編集する際に、対応する@Babelコンポーネントを使用します。これらの対応言語の使用コンポーネントを公式サイトで見つけ、プロジェクトにインポートし、.babelrcファイルでコンポーネントを設定することで、ESLint+Babelモードを使用してコードの品質をチェックし、向上させることができます。
8. airbnbとstandardルールセット
上記ではPrettier、Babel、ESLintの統合使用について説明しました。しかし、実際の開発では、ESLintとこれらのサードパーティコンポーネントを連携させるプロセスは非常に煩雑で面倒です。バージョンの競合や互換性、言語のコンパイルと解析などの問題を解決する必要があります。これらの検証、フォーマット、コンパイル、トランスパイルコンポーネントのルール設定情報が増えると、コンポーネント間の競合とメンテナンスが非常に困難になります。設定ファイルが複雑で理解しにくくなり、奇妙な問題が発生することがあります。これらをデバッグするために大量の時間を費やす必要があり、プロジェクトのメンテナンスが非常に困難になります。これらの問題を解決するために、複雑なコンポーネント関係や設定ファイル内の様々なルール設定をメンテナンスする必要のない、一式のルール検証コンポーネントが登場しました。私たちは、これらの一式のルールコンポーネントを直接インポートし、プロジェクトでこの一式のルールコンポーネントのみを設定およびメンテナンスするだけで済みます。
現在、人気のある standard と airbnb の2つのルールセットがあります。これらは現在最も多く使用され、最も人気があり、全体的な実践効果が最も良いルールセットです。私たちは、これらのルールセットの機能を直接利用し、他のコンポーネントを設定して品質を検証する必要はありません。 standard と airbnb の検証コンポーネントは、プロジェクトでコードの潜在的なエラーや問題を簡単に検出し、プロジェクトの品質とメンテナンス性を保証するのに役立ちます。もしあなたがこれまでairbnbのような検証ルールを使用してプロジェクトコードを検証したことがない場合、あなたが書いたコードのあらゆる場所にエラーが発生する可能性があります。
1. airbnb
airbnbコンポーネントをプロジェクトにインポートします。その検証ルールのプロパティは、https://github.com/lin-123/javascriptで確認できます。
npm install --save-dev @vue/eslint-config-airbnb
npm install --save-dev eslint-config-airbnb-base
ESLintの設定ファイル .eslintrc.cjs の extends プロパティに '@vue/airbnb' を設定すると、複数のルールセットの内容を同時に設定できます。
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
'plugin:vue/vue3-essential',
'@vue/airbnb',
],
"overrides": [
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'vuejs-accessibility/click-events-have-key-events': 'off',
}
}
npm run lint検証コマンドを実行すると、プロジェクトのコードがairbnbで設定された検証ルールで実行されていることがわかります。
npm run lint
npm run lint -- --fix
standardの使用
standardの使用はairbnbと基本的に同じです。プロジェクトにその基本コンポーネントパッケージとeslint互換パッケージをインポートし、eslintでこのstandardルールを読み込みます。standardのすべての検証ルールは、https://github.com/standard/standard/blob/master/docs/RULES-zhcn.md#javascript-standard-styleで確認できます。
npm install standard --save-dev
npm install @vue/eslint-config-standard --save-dev
//.eslintrc.cjsファイルに追加
module.exports = {
"extends": [
'plugin:vue/vue3-essential',
'@vue/standard'
],
}
//検証と自動修正
npm run lint
npm run lint -- --fix
実際の開発では、プロジェクトの状況に応じて最適な組み合わせを選択してください。
- ESLint
- ESLint+Prettier
- ESLint+Prettier+Babel
- ESLint+airbnb
- ESLint+standard
9. TypeScriptプロジェクトでのESLint
TypeScriptタイプのプロジェクトにESLintのTypeScriptルール検証を追加する方法は2つあります。1つ目は、初期化コマンドを使用してTypeScript検証に必要なパッケージをインポートする方法です。
npm init vite@latest ESLint-TypeScript
cd ESLint-TypeScript
npm install
//Vueプロジェクト用のeslintプラグインをインストール
npm install eslint --save-dev
//Vueプロジェクト用のeslintプラグインをインストール
npm install eslint-plugin-vue --save-dev
npm init @eslint/config
? How would you like to use ESLint? ...
To check syntax only //構文のみをチェック
> To check syntax and find problems //構文をチェックし問題を見つける
? What type of modules does your project use? ...
> JavaScript modules (import/export)
? Which framework does your project use? ...
React
> Vue.js
? Does your project use TypeScript? » No / Yes
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
? Which package manager do you want to use? ...
> npm
yarn
pnpm
既存のESLintプロジェクトでは、初期化方式を使用せずにTypeScript-ESLintを作成できます。npmインポート方式でTypeScript-ESLintのルール検証パッケージを直接インポートできます。
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-vue
- @typescript-eslint/parser: ESLintがTypeScriptのパーサーを読み込めるようにします。
- @typescript-eslint/eslint-plugin: TypeScript用のLintルールのプラグインを提供します。
.eslintrc.cjsファイルの設定
.eslintrc.cjsファイルの parserOptions 要素に parser プロパティと値 '@typescript-eslint/parser' を追加し、構文検証時にTypeScriptの構文内容を検証できます。
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential",
"plugin:@typescript-eslint/recommended",
],
"overrides": [
],
"parser": "vue-eslint-parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"parser": "@typescript-eslint/parser",
},
"plugins": [
"vue"
],
"rules": {
}
}
"parser": "vue-eslint-parser" この文は非常に重要で、必ず追加する必要があります。
"lint": "eslint --ext .js,.vue,.ts src"
"lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix"
Prettierの設定
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential",
"plugin:@typescript-eslint/recommended",
"@vue/prettier",
],
"overrides": [
],
"parser": "vue-eslint-parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"parser": "@typescript-eslint/parser",
},
"plugins": [
"vue",
"@typescript-eslint"
],
"rules": {
}
}
standardルールの導入
eslint+typescriptプロジェクト環境でstandardルールコンポーネントを追加するには、まず standard-with-typescript パッケージをプロジェクトに導入する必要があります。
npm install @vue/eslint-config-standard-with-typescript --save-dev
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"plugin:vue/vue3-essential",
'@vue/eslint-config-standard-with-typescript'
],
"overrides": [
],
"parser": "",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
},
"plugins": [
"vue"
],
"rules": {
//vite/clientのインポートルールを無効にする
'@typescript-eslint/triple-slash-reference': 'off'
}
}