[Vue3+Vite+TS project integrates ESlint + Prettier to realize code specification checking and code formatting]

foreword

This article mainly explains how to integrate Eslint + Perttier in the Vue3 + ts project created by Vite to implement code specification checking and configure the automatic formatting of the saved code in the vscode editor, because the project created through vite does not have the eslint code checking function by default. , but in projects developed by multiple people, the code checking and code formatting functions are indispensable, so here is a summary in the form of a blog, hoping to be helpful to the veterans, if the veterans think it is helpful to you, please click Like + favorite, hope to help more people!

create project

I am here to create a vue3 + ts project directly through the default template provided by vite

# 如果npm 的版本是6.x版本,则使用下面这条命令创建项目
npm create vite@latest vite-vue3-ts --template vue-ts

# 如果npm 的版本是7+ 以上版本,则使用以下命令
npm create vite@latest vite-vue3-ts -- --template vue-ts

Such a vue3 + ts project is created, use vscode to open the project, and then execute npm i to install
dependencies After the dependency installation is complete, execute npm run dev to start the project and it can be accessed normally in the browser.
insert image description here

Install and initialize ESlint

Install ESlint:

# 安装eslint
npm i eslint -D

Initialize ESlint:

  • Execute npx eslint --initthe command to initialize eslint
  • Follow the prompts to select the following options in turn
You can also run this command directly using 'npm init @eslint/config'.
 
? How would you like to use ESLint? ...
To check syntax and find problems
 
? What type of modules does your project use? ...
JavaScript modules (import/export)
 
? Which framework does your project use? ...
Vue.js
 
? Does your project use TypeScript? » No / Yes
Yes
 
? Where does your code run? ... (用空格选中两个,回车确定)
√ Browser
√ Node
 
? What format do you want your config file to be in? ...
JavaScript
 
The config that you've selected requires the following dependencies:
eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
? Would you like to install them now?
No
  • The last one prompts us to choose No, and then manually npm installs the prompted dependencies
npm i -D eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest 
  • After the initialization is complete, you will see a .eslintrc.cjs file in the project root directory, which is the eslint configuration file
module.exports = {
    
    
    "env": {
    
    
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential",
        "plugin:@typescript-eslint/recommended"
    ],
    "overrides": [
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
    
    
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
    
    
    }
}
  • In package.json, add the command
 "scripts": {
    
    
 	// 执行该命令eslint会检测当前项目下所有的.vue,.js,.ts,.jsx,.tsx文件是否符合eslint的代码规范,并尝试自动修复
    "lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix"
  },
  • Execute npm run lintthe command, you will see the following error
    insert image description here
  • Modify the .eslintrc.cjs file
module.exports = {
    
    
  "env": {
    
    
      "browser": true,
      "es2021": true,
      "node": true
  },
  "extends": [
      "eslint:recommended",
      "plugin:vue/vue3-essential",
      "plugin:@typescript-eslint/recommended"
  ],
  "overrides": [
  ],
  // 配置解析vue文件
  "parser":"vue-eslint-parser",
  "parserOptions": {
    
    
      "ecmaVersion": "latest",
      "parser": "@typescript-eslint/parser",
      "sourceType": "module"
  },
  "plugins": [
      "vue",
      "@typescript-eslint"
  ],
 // 添加规则
 "rules": {
    
    
   "@typescript-eslint/ban-types": [
      "error",
      {
    
    
          "extendDefaults": true,
          "types": {
    
    
              "{}": false
          }
      }
    ]
  }
}

Then re-execute npm run lintthe command and there will be no error.

Install and configure Prettier

Install prettier:

npm install prettier -D

Configure prettier:

Create the .prettierrc.cjs file in the root directory of the project. This file is the configuration file of Prettier. You can configure the rules of Prettier formatting code in this file. Add the configuration as follows:

// prettier的默认配置文件
module.exports = {
    
    
  // 一行最多 100 字符
  printWidth: 100,
  // 使用 2 个空格缩进
  tabWidth: 2,
  // 不使用缩进符,而使用空格
  useTabs: false,
  // 不尾随分号
  semi: false,
  // 使用单引号
  singleQuote: true,
  // 多行逗号分割的语法中,最后一行不加逗号
  trailingComma: 'none',
   // 单个参数的箭头函数不加括号 x => x
  arrowParens: 'avoid',     
  // 对象大括号内两边是否加空格 { a:0 }
  bracketSpacing: true,      
}

Configure VScode to automatically format code when saving

Install the following two plugins in vscode:

  • ESLint: Install this plugin, it will automatically find the ESlint rules in the project, give verification prompts, ESlint can also format the code
  • Prettier - Code formatter: Install this plugin to format the code, but does not pay attention to the inspection of potential problems in code quality
    insert image description here
    insert image description here

Modify the configuration file of vscode:

Open: File -> Preferences -> Settings -> Edit in settings.json

insert image description here
insert image description here
Add some configuration in the settings.json file:

{
    
    
  // vscode默认启用了根据文件类型自动设置tabsize的选项
  "editor.detectIndentation": false,
  // 重新设定tabsize
  "editor.tabSize": 2,
  // 每次保存的时候自动格式化
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    
    
    // 使用eslint来fix,包括格式化会自动fix和代码质量检查会给出错误提示
    "source.fixAll.eslint": true
  },
  // 把prettier设置为vscode默认的代码格式化工具
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  // vue文件的默认格式化工具选择prettier
  "[vue]": {
    
    
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Configured here When we save the code in the vscode editor, the code can be automatically formatted!

Resolving conflicts between ESLint and Prettier

Reason for conflict:

Because both ESLint and Prettier can perform code formatting, and we have enabled ESLint and Prettier for code formatting in the settings.json file at the same time, so when the overlapping formatting rules of the two are inconsistent, it will cause conflicts when formatting code question.

To resolve conflicts:

Install eslint-config-prettier and eslint-plugin-prettier dependencies:

npm install eslint-config-prettier eslint-plugin-prettier -D
  • eslint-config-prettier will turn off the configuration of code formatting in ESLint
  • eslint-plugin-prettier Configure Prettier as a plugin for ESLint and let it run as a linter rule

Then add a configuration at the end of extends in .eslintrc.cjs:

  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-essential',
    'plugin:@typescript-eslint/recommended',
    "plugin:prettier/recommended" // 解决ESlint和Prettier冲突
  ],

After this configuration, ESLint will ignore the formatting rules that overlap with Prettier when formatting, and these will be formatted by Prettier, thus solving the conflict between ESlint and Prettier.

Automatically detect eslint specifications when configuring vite to run

When vite is running, it will not automatically detect the eslint specification by default. As shown in the figure below, we declared the variable a in the main.ts file, but it is not used, but vite can run normally but does not give eslint warning, but when the command is npm run lintexecuted You can see the warning message of eslint.
insert image description here
If you want to automatically detect the eslint specification when vite is running, you only need to install the vite-plugin-eslint dependency and add related configurations.

Install vite-plugin-eslint:

npm install vite-plugin-eslint -D

Configure the vite.config.ts file:

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

// https://vitejs.dev/config/
export default defineConfig({
    
    
  plugins: [
    vue(),
    // 配置vite在运行的时候自动检测eslint规范
    eslintPlugin({
    
    
      include: ['src/**/*.ts', 'src/**/*.js', 'src/**/*.vue', 'src/*.ts', 'src/*.js', 'src/*.vue']
    })
  ]
})

After adding the configuration of the vite-plugin-eslint plugin in the vite.config.ts file, you will see that vite performs eslint specification checks on the code when it is running.
insert image description here
The above is the specific implementation of integrating ESlint + Prettier in the Vue3+Vite+TS project to achieve code specification checking and code formatting. I hope it will be helpful to all veterans!

Guess you like

Origin blog.csdn.net/m0_37873510/article/details/128692295