打造丝滑编码体验:Vite+ESLint+Prettier项目搭建与实用配置全攻略

773 阅读6分钟

简介

在开发过程中,保持代码风格的一致性和规范性对于团队协作和代码维护至关重要。为此,我在搭建博客项目时,选择了Eslint和Prettier这两个强大的工具来协助我实现代码的自动校验和格式化。下面我将详细记录配置过程,以便有需要的开发者参考

创建Vue3.2项目

一、环境要求

node >= 16 // 实测12.22.12中初始化会报错

打开命令行输入以下指令

npm init vue@latest

这一指令将会安装并执行create-vue,它是 Vue 官方的项目脚手架工具。你将会看到一些诸如 TypeScript 和测试支持之类的可选功能提示:

✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add Cypress for both Unit and End-to-End testing? … No / Yes
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes

而我个人选择的搭配方式是:Typescript+JSX+VueRouter+Pinia+ESlint+Prettier

二、设置VSCode

安装vscode插件

image.png

image.png

image.png

配置当前项目.vscode

image.png

image.png

extensions.json

{
  "recommendations": ["dbaeumer.vscode-eslint"]
}

settings.json 设置ctrl + s保存自动按照prettier格式化

{
  "editor.codeActionsOnSave": {
      "source.fixAll": true,
  },
  "eslint.validate": [
      "javascript",
      "javascriptreact",
      "typescript",
      "typescriptreact",
  ],
  "eslint.alwaysShowStatus": true,
  "editor.formatOnSave": true
  // "vue.features.codeActions.enable": false  
}
 

注意:如果vscode识别比较慢,可以将自动识别导入包功能关闭,加上 "vue.features.codeActions.enable": false 就不会有下面提示了

image.png

三、安装插件

安装 vite-plugin-eslint

说明: 该包是用于配置vite运行的时候自动检测eslint规范
问题: 不装这个包可以吗? 答案是“可以的”,使用npm run dev时并不会主动检查代码
npm i vite-plugin-eslint --save-dev

配置.eslintrc.js

0、ESLint配置文档

image.png

module.exports = {
    "extends": [
        "plugin:@typescript-eslint/recommended",
        "eslint-config-airbnb-base",
        "@vue/typescript/recommended",
        "plugin:vue/vue3-recommended",
        "plugin:vue-scoped-css/base",
        "plugin:prettier/recommended"
    ],
    "env": {
        "browser": true,
        "node": true,
        "jest": true,
        "es6": true
    },
    "globals": {
        "defineProps": "readonly",
        "defineEmits": "readonly"
    },
    "plugins": ["vue", "@typescript-eslint"],
    "parserOptions": {
        "parser": "@typescript-eslint/parser",
        "sourceType": "module",
        "allowImportExportEverywhere": true,
        "ecmaFeatures": {
        "jsx": true
        }
    },
    "settings": {
        "import/extensions": [".js", ".jsx", ".ts", ".tsx"]
    },
    "rules": {
        "no-console": "off",
        "no-continue": "off",
        "no-restricted-syntax": "off",
        "no-plusplus": "off",
        "no-param-reassign": "off",
        "no-shadow": "off",
        "guard-for-in": "off",
        "prettier/prettier": "off", // 解决replace with


        "import/extensions": "off",
        "import/no-unresolved": "off",
        "import/no-extraneous-dependencies": "off",
        "import/prefer-default-export": "off",
        "import/first": "off", // https://github.com/vuejs/vue-eslint-parser/issues/58
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "vue/first-attribute-linebreak": 0,

        "@typescript-eslint/no-unused-vars": [
        "error",
        {
            "argsIgnorePattern": "^_",
            "varsIgnorePattern": "^_"
        }
        ],
        "no-unused-vars": [
        "error",
        {
            "argsIgnorePattern": "^_",
            "varsIgnorePattern": "^_"
        }
        ],
        "no-use-before-define": "off",
        "@typescript-eslint/no-use-before-define": "off",
        "@typescript-eslint/ban-ts-comment": "off",
        "@typescript-eslint/ban-types": "off",
        "class-methods-use-this": "off" // 因为AxiosCancel必须实例化而能静态化所以加的规则,如果有办法解决可以取消
    },
    "overrides": [
        {
        "files": ["*.vue"],
        "rules": {
            "vue/component-name-in-template-casing": [2, "kebab-case"],
            "vue/require-default-prop": 0,
            "vue/multi-word-component-names": 0,
            "vue/no-reserved-props": 0,
            "vue/no-v-html": 0,
            "vue-scoped-css/enforce-style-type": ["error", { "allows": ["scoped"] }]
        }
        },
        {
        "files": ["*.ts", "*.tsx"], // https://github.com/typescript-eslint eslint-recommended
        "rules": {
            "constructor-super": "off", // ts(2335) & ts(2377)
            "getter-return": "off", // ts(2378)
            "no-const-assign": "off", // ts(2588)
            "no-dupe-args": "off", // ts(2300)
            "no-dupe-class-members": "off", // ts(2393) & ts(2300)
            "no-dupe-keys": "off", // ts(1117)
            "no-func-assign": "off", // ts(2539)
            "no-import-assign": "off", // ts(2539) & ts(2540)
            "no-new-symbol": "off", // ts(2588)
            "no-obj-calls": "off", // ts(2349)
            "no-redeclare": "off", // ts(2451)
            "no-setter-return": "off", // ts(2408)
            "no-this-before-super": "off", // ts(2376)
            "no-undef": "off", // ts(2304)
            "no-unreachable": "off", // ts(7027)
            "no-unsafe-negation": "off", // ts(2365) & ts(2360) & ts(2358)
            "no-var": "error", // ts transpiles let/const to var, so no need for vars any more
            "prefer-const": "error", // ts provides better types with const
            "prefer-rest-params": "error", // ts provides better types with rest args over arguments
            "prefer-spread": "error", // ts transpiles spread to apply, so no need for manual apply
            "valid-typeof": "off" // ts(2367)
        }
        }
    ]
}

上面代码中,所需要到的

"plugin:@typescript-eslint/recommended",
"eslint-config-airbnb-base",
"@vue/typescript/recommended",
"plugin:vue/vue3-recommended",
"plugin:vue-scoped-css/base",
"plugin:prettier/recommended"

需要依次安装下

1、eslint-config-airbnb-base

npm install eslint-config-airbnb-base --save-dev

可以实现代码驼峰转换 <documentationIcon />转换为<documentation-icon />

2、eslint-plugin-vue-scoped-css

npm install eslint-plugin-vue-scoped-css --save-dev

遇到Bug

image.png

解决方法:

  1. 在.eslintrc.js 文件中的rules中添加 “prettier/prettier”: “off”

  2. 重启vscod 再重启项目就解决了

ESLint 和 Prettier 配合使用

prettier官方提供了一款工具 eslint-config-prettier 来解决这个问题。

本质上这个工具其实就是禁用掉了一些不必要的以及和Prettier相冲突的ESLint规则。

安装依赖:

npm install --save-dev eslint-config-prettier

修改 eslintrc 文件

// 在 extends 部分加入 prettier 即可
{
  "extends": [
    "...",
    "prettier"
  ]
}

说到整合使用 ESLint 和 Prettier,这事儿其实挺有意思的。想象一下,你有个调皮捣蛋的弟弟,每次你刚把房间收拾得整整齐齐,他就来捣蛋一通,弄得乱七八糟。这时候,ESLint 就是那个爱干净的哥哥,而 Prettier 就是那个超级厉害的扫地机器人。

ESLint 哥哥负责检查房间里的各种小细节,看看哪里不对头,比如地上有没有乱丢的玩具、床上是不是乱糟糟的。而 Prettier 扫地机器人呢,它不管三七二十一,先把整个房间扫一遍,确保地面干净整洁。

但问题是,有时候 Prettier 扫地机器人扫得太快了,会把 ESLint 哥哥刚收拾好的一些小东西给弄乱。这时候,eslint-plugin-prettier 就来当和事佬了。它告诉 ESLint 哥哥:“哎呀,别那么挑剔嘛,Prettier 已经扫过一遍了,现在房间看起来挺干净的呀!”

于是,ESLint 哥哥就放宽了心,不再为那些小细节纠结。而当你发现房间还是有些小瑕疵时,只需要对 ESLint 哥哥说一声:“嘿,eslint --fix 一下!”它就会和 Prettier 一起,再次把房间打扫得干干净净。

这样一来,你既可以享受到 Prettier 带来的快速清扫,又可以确保房间符合 ESLint 的高标准。两者相辅相成,让你的代码既整洁又规范

例如:

image.png

这样就相当于将 Prettier 整合进了 ESLint 中。

安装依赖:

npm install --save-dev eslint-plugin-prettier
npm install --save-dev prettier

修改 eslintrc 文件

{
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}

重点贴码

其实可以简化一下,直接 extend 一下 plugin:prettier/recommended 即可。

如下:

{
  "extends": ["plugin:prettier/recommended"]
}

上面这行配置,实际上相当于:

{
  "extends": ["prettier"],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off"
  }
}

补充内容

如果需要在其他开发工具上也保持一致的代码格式,推荐设置 .editorconfig

# 表示是最顶层的配置文件,发现值为true时,才会停止查找.editorconfig文件
root = true
[*]
# 设置使用那种缩进风格(tab是制表符,space是空格)
indent_style = space

# 设置换行符,值为lf、cr和crlf
end_of_line = auto
charset = utf-8
# 设置为true则删除换行符之前的任何空白字符
# 设置为true会删除每一行后的任何空格  ***
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[*.{ts,js,vue,css}]
indent_size = 2

遇到坑洼

一、vscod:less文件被自动格式化,如果需要关闭 设置vscode settings,如果想不影响到其他项目,就在当前项目下的.vscode设置就可以了 全局样式启用less格式化则

  "[less]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
 "[less]": {
    "editor.defaultFormatter": null
  },