Vite2+Vue3+ts的eslint設置踩坑


新項目了

渾渾噩噩一個五年前的vue2的項目維護了一年多,要開始重構了。前端還是vue2,要加個后台系統來管理配置化功能。后台管理就撿起vue3吧,好久沒寫了,看看有啥新東西玩,有空了再更新一下博客。

Vite搭建

之前寫了個用vue-cli來搭建的(vue-cli腳手架搭建vue3.0+typescripe項目),還是Vue3剛出來那會踩的坑,現在vite逐漸成熟,性能、速度也比webpack要好,也來踩踩的。
Vite官網已經寫的很詳細了,不贅述,無坑。
yarn create vite vue-app --template vue-ts

eslint

先安裝eslint

yarn add -D eslint

創建.eslintrc.js

先來點基本配置

  module.exports = {
    root: true,
    env: {
  	node: true,
  	browser: true,
  	es2021: true,
    },
    parserOptions: {
  	ecmaVersion: 12,
    },
  }

引入規則

我這里就用幾個官方規范吧,下面總是要自己配置一堆的,也可以用其他的優秀開源規范(Airbnb
yarn add -D eslint-plugin-vue
.eslintrc中extends添加'plugin:vue/vue3-recommended'

Airbnb

如果要用Airbnb,需要安裝eslint-config-airbnb-baseeslint-plugin-import

yarn add -D eslint-config-airbnb-base eslint-plugin-import

.eslintrc中extends添加'airbnb-base'

配合prettier

yarn add -D eslint-plugin-prettier eslint-config-prettier
yarn add -D -E prettier

.eslintrc差不多就寫成這樣

  ……
  extends: [
  	'plugin:vue/vue3-recommended',
  	'eslint:recommended',
  	'plugin:prettier/recommended'
  ],
  plugins: [ 'prettier'],
  rules: {
  	'prettier/prettier': 0,
  }
  ……

對ts的支持

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

.eslintrc中添加配置

plugins: ['@typescript-eslint'],
parserOptions: {
  parser: '@typescript-eslint/parser'
}

.eslintrc.js

至此,eslint配置完成,可以正常使用,上代碼

  module.exports = {
    root: true,
    env: {
  	node: true,
  	es2021: true,
  	browser: true
    },
    extends: [
  	'plugin:vue/vue3-recommended',
  	'eslint:recommended',
  	'plugin:prettier/recommended'
    ],
    plugins: ['@typescript-eslint', 'prettier'],
    parserOptions: {
  	parser: '@typescript-eslint/parser',
  	ecmaVersion: 12
    },
    rules: {
  	'prettier/prettier': 0,
  	……
    }
  }

在頁面上查看eslint報錯

強逼迫福音,經常有時候沒注意看命令行,報錯就一直留下來,提交代碼也會被攔住。添加vite-plugin-eslint插件即可
在vite.config.ts中配置

  import { defineConfig } from 'vite'
  import vue from '@vitejs/plugin-vue'
  import eslintPlugin from 'vite-plugin-eslint'

  export default defineConfig({
    plugins: [
  	vue(),
  	eslintPlugin({
  	  exclude: ['./node_modules/**'],
  	  cache: false
  	})
    ]
  })

記筆記!cache這個屬性一定要帶上false,否則修復的問題還是會不停報出來錯,有毒。

使用setup sugar的坑

<script setup>支持不return直接用,使用eslint舊版會報錯
'xxx' is assigned a value but never used.
在.eslintrc配置'no-unused-vars': [0]可解決
我試了新版本沒有這個問題,在template里面使用變量就不會標紅報錯

使用defineProps時eslint會報錯,說未定義
image
這個時候如果你在vue中引入defineProps
import { defineProps } from 'vue'
那么你會得到另一個報錯

[@vue/compiler-sfc] `defineProps` is a compiler macro and no longer needs to be imported.

解決方法:
在.eslintrc中,添加配置

env: {
  // ...
  'vue/setup-compiler-macros': true
}

cool~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM