Guide to using eslint+prettier+husky in vue3+ts+vite project

Create project

Use the vue-ts template to create a project. Since the focus of this article is not the construction of the project, it is briefly mentioned here.

pnpm create vite my-vue-app --template vue-ts

Why do you need eslinttoprettier

This article is mainly based on actual combat, so I won't go eslintinto details here prettier. Students who are not clear can check the relevant information. Simply put, it eslintcan ensure the quality of the project, and prettiercan ensure the uniform format and style of the project.

configure eslint

Execute the installation command

pnpm add eslint -D

Execute the eslint initialization command

npx eslint --init

Initialize options in sequence

image.png

(1) How would you like to use ESLint?
选择:To check syntax and find problems

(2) What type of modules does your project use?
选择:JavaScript modules (import/export)

(3) Which framework does your project use?
选择:Vue.js

(4) Does your project use TypeScript?
选择:Yes

(5) Where does your code run?
选择:Browser

(6) What format do you want your config file to be in?
选择:JavaScript

(7) Would you like to install them now?
选择:Yes

(8) Which package manager do you want to use?
选择:pnpm

After the dependency installation is complete, a .eslintrc.jsconfiguration file will be generated

module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential",
        "plugin:@typescript-eslint/recommended"
    ],
    "parserOptions": {
        "ecmaVersion": "latest",
        "parser": "@typescript-eslint/parser",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
    }
}

.eslintrc.jsAt this time , an error will appear when opening the configuration file, and you need to envadd node: trueconfiguration to the field to solve the error that eslint cannot find the module

image.png

module.exports = {
    "env": {
        "browser": true,
        "es2021": true,
        // 新增
+        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential",
        "plugin:@typescript-eslint/recommended"
    ],
    "parserOptions": {
        "ecmaVersion": "latest",
        "parser": "@typescript-eslint/parser",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
    }
}

Add the command in the package.jsonfilescriptlint

{
    "scripts": {
        // eslint . 为指定lint当前项目中的文件
        // --ext 为指定lint哪些后缀的文件
        // --fix 开启自动修复
        "lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix"
    }
}

execute lintcommand

pnpm lint

image.pngAt this time, the error in the above figure will be displayed on the command line, which means that .vuea parsing error occurs when parsing the suffixed file parsing error.

After consulting the information, I found that the suffix file eslintwill not be parsed by default . .vueTherefore, an additional parser is required to parse .vuesuffix files.

But when we look at .eslintrc.jsthe file, we extendswill find that there is already an inherited "plugin:vue/vue3-essential"configuration. Then node_modulesyou can find eslint-plugin-vue/lib/cinfigs/essentialit in , where the configuration extendsis inherited from the same level directory, and you will find this configuration base.jsinside . Therefore, it stands to reason that the suffix file parser: require.resolve('vue-eslint-parser')should be parsed ..vue

继续往下看.eslintrc.js文件中的extends会发现,extends中还有一个"plugin:@typescript-eslint/recommended",它是来自于/node_modules/@typescript-eslint/eslint-plugin/dist/configs/recommended.js,查看该文件会发现最终继承于同级目录下的base.js文件。从该文件中可以发现parser: '@typescript-eslint/parser',配置。

按照.eslintrc.js文件中的extends配置的顺序可知,最终导致报错的原因就是@typescript-eslint/parservue-eslint-parser覆盖了。

{
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential",
        "plugin:@typescript-eslint/recommended"
    ],
}

查看eslint-plugin-vue官方文档可知。如果已经使用了另外的解析器(例如"parser": "@typescript-eslint/parser"),则需要将其移至parseOptions,这样才不会与vue-eslint-parser冲突。

修改.eslintrc.js文件

module.exports = {
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "vue-eslint-parser",
    "parserOptions": {
        "ecmaVersion": "latest",
        "parser": "@typescript-eslint/parser",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
    }
}

两个parser的区别在于,外面的parser用来解析.vue后缀文件,使得eslint能解析<template>标签中的内容,而parserOptions中的parser,即@typescript-eslint/parser用来解析vue文件中<script>标签中的代码。

此时,再执行pnpm lint,就会发现校验通过了。

安装vscode插件ESLint

如果写一行代码就要执行一遍lint命令,这效率就太低了。所以我们可以配合vscode的ESLint插件,实现每次保存代码时,自动执行lint命令来修复代码的错误。

在项目中新建.vscode/settings.json文件,然后在其中加入以下配置。

{
    // 开启自动修复
    "editor.codeActionsOnSave": {
        "source.fixAll": true
    }
}

配置prettier

执行安装命令

pnpm add prettier -D

在根目录下新建.prettierrc.js

添加以下配置,更多配置可查看官方文档

module.exports = {
    // 一行的字符数,如果超过会进行换行,默认为80
    printWidth: 80, 
    // 一个tab代表几个空格数,默认为80
    tabWidth: 2, 
    // 是否使用tab进行缩进,默认为false,表示用空格进行缩减
    useTabs: false, 
    // 字符串是否使用单引号,默认为false,使用双引号
    singleQuote: true, 
    // 行位是否使用分号,默认为true
    semi: false, 
    // 是否使用尾逗号,有三个可选值"<none|es5|all>"
    trailingComma: "none", 
    // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
    bracketSpacing: true
}

package.json中的script中添加以下命令

{
    "scripts": {
        "format": "prettier --write ./**/*.{html,vue,ts,js,json,md}"
    }
}

运行该命令,会将我们项目中的文件都格式化一遍,后续如果添加其他格式的文件,可在该命令中添加,例如:.less后缀的文件

安装vscode的Prettier - Code formatter插件

安装该插件的目的是,让该插件在我们保存的时候自动完成格式化 在.vscode/settings.json中添加一下规则

{
    // 保存的时候自动格式化
    "editor.formatOnSave": true,
    // 默认格式化工具选择prettier
    "editor.defaultFormatter": "esbenp.prettier-vscode"
}

解决eslintprettier的冲突

在理想的状态下,eslintprettier应该各司其职。eslint负责我们的代码质量,prettier负责我们的代码格式。但是在使用的过程中会发现,由于我们开启了自动化的eslint修复与自动化的根据prettier来格式化代码。所以我们已保存代码,会出现屏幕闪一起后又恢复到了报错的状态。

这其中的根本原因就是eslint有部分规则与prettier冲突了,所以保存的时候显示运行了eslint的修复命令,然后再运行prettier格式化,所以就会出现屏幕闪一下然后又恢复到报错的现象。这时候你可以检查一下是否存在冲突的规则。

查阅资料会发现,社区已经为我们提供了一个非常成熟的方案,即eslint-config-prettier + eslint-plugin-prettier

  • eslint-plugin-prettier: 基于 prettier 代码风格的 eslint 规则,即使eslint使用pretter规则来格式化代码。
  • eslint-config-prettier: 禁用所有与格式相关的 eslint 规则,解决 prettier 与 eslint 规则冲突,确保将其放在 extends 队列最后,这样它将覆盖其他配置

安装依赖

pnpm add eslint-config-prettier eslint-plugin-prettier -D

在 .eslintrc.jsonextends的最后添加一个配置

{ 
    extends: [
    'eslint:recommended',
    'plugin:vue/vue3-essential',
    'plugin:@typescript-eslint/recommended',
+    // 新增,必须放在最后面
+    'plugin:prettier/recommended' 
  ],
}

最后重启vscode,你会发现冲突消失了,eslintprettier也按照我们预想的各司其职了。

配置husky

虽然上面已经配置好了eslintpreitter,但是还是存在以下问题。

对于不使用vscode的,或者没有安装eslintpreitter插件的同学来说,就不能实现在保存的时候自动的去修复与和格式化代码。

这样提交到git仓库的代码还是不符合要求的。因此需要引入强制的手段来保证提交到git仓库的代码时符合我们的要求的。

husky是一个用来管理git hook的工具,git hook即在我们使用git提交代码的过程中会触发的钩子。

安装依赖

pnpm add husky -D

package.json中的script中添加一条脚本命令

{
    "scripts": {
        "prepare": "husky install"
    },
}

该命令会在pnpm install之后运行,这样其他克隆该项目的同学就在装包的时候就会自动执行该命令来安装husky。这里我们就不重新执行pnpm install了,直接执行pnpm prepare,这个时候你会发现多了一个.husky目录。

然后使用husky命令添加pre-commit钩子,运行

npx husky add .husky/pre-commit "pnpm lint && pnpm format"

执行完上面的命令后,会在.husky目录下生成一个pre-commit文件

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pnpm lint && pnpm format

现在当我们执行git commit的时候就会执行pnpm lintpnpm format,当这两条命令出现报错,就不会提交成功。以此来保证提交代码的质量和格式。

安装依赖说明

  • eslint: JavaScript 和 JSX 检查工具
  • eslint-plugin-vue: 使用 ESLint 检查 .vue文件 的 <template><script>,以及.js文件中的Vue代码

总结

本篇文章主要是以一个vue-ts-vite的项目的搭建为基础,在项目中引入eslint + prettier + husky来规范项目。完整的代码一上传至github点击此处可以查看完整代码。

参考文章

# 实战--为vite-vue3-ts项目添加 eslint + prettier + lint-staged 项目规范

Guess you like

Origin juejin.im/post/7118294114734440455