はじめに
TypeScriptの場合も、これからはESLintらしい。
- TypeScript on ESLint の未来
- [さよならTSLint、お久しぶりESLint]
(https://k2ss.info/archives/2689)
Vue CLIのV3を使って、TypeScript+ESLintの初期構築手順をまとめる。
手順
vue-cliのインストール
# npm i -g @vue-cli
# vue -V
3.11.0
Vue CLIによるプロジェクト作成
# vue create myproject
マニュアルを選択
? Please pick a preset:
default (babel, eslint)
❯ Manually select features
インストールしたい機能を選択する。
TypeScript
とLinter / Formatter
を有効化。その他はお好みで。
? Check the features needed for your project:
◉ Babel
◉ TypeScript
◯ Progressive Web App (PWA) Support
◉ Router
◉ Vuex
◉ CSS Pre-processors
❯◉ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
以降は有効化した機能に関する質問が続く。
Linterとフォーマッタに関する質問で、ESLint + Prettier
を選択。
? Pick a linter / formatter config:
TSLint
ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
❯ ESLint + Prettier
それ以外の質問はお好みでOK。
VSCodeの設定追加
ESLintの拡張機能を追加。
ESLint
さらに、プロジェクト設定を追加。
setting.json
{
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
{
"language": "typescript",
"autoFix": true
},
{
"language": "vue",
"autoFix": true
}
],
}
Prettierの設定追加
.prettierrc
をルートディレクトリに追加する。
{
"tabWidth": 2,
"semi": true,
"singleQuote": true
}
.eslintrc.js
のrulesに追加してもOK
.eslintrc.js
module.exports = {
root: true,
env: {
node: true
},
extends: ["plugin:vue/essential", "@vue/prettier", "@vue/typescript"],
rules: {
"no-console": process.env.NODE_ENV === "production" ? "error" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",
// 以下を追加
"prettier/prettier": [
"error",
{
"singleQuote": true,
"semi": false
}
]
},
parserOptions: {
parser: "@typescript-eslint/parser"
}
};
ESLintの実行
デフォルトの設定だと、Linterが勝手に修正してしまう。
https://teratail.com/questions/186587
無効化したい場合は、package.json
を修正する
package.json
{
"name": "myproject",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
// --no-fixを追加
"lint": "vue-cli-service lint --no-fix",
// 追加
"lint:fix": "vue-cli-service lint"
},
"dependencies": {
// 各種ライブラリ
},
"devDependencies": {
// 各種ライブラリ
}
ESLintを実行
# npm run lint
警告が多数検出されたら、正常に動作している。
warning: Replace `"Avenir"` with `'Avenir'` (prettier/prettier) at src/App.vue:13:16:
補足
既存のプロジェクトをTSLintからESLintに切り替える場合は、色々ライブラリを追加する必要があるみたい
Vue.jsでtypescript-eslint + Prettierを導入する