Vue3 + Eslint + prettier

发布时间 2023-08-15 17:44:13作者: 小短腿奔跑吧

一、背景

公司内部团队大部分由多人组成,当遇到多个前端开发同一个项目时,代码规范及代码质量,是需要考虑的一个重中之重

二、Eslint + prettier 是什么

ESLint 的主要功能包含代码格式代码质量的校验,而 Prettier 只是代码格式的校验,不会对代码质量进行校验。
代码格式问题:单行代码长度、tab 长度、空格、逗号表达式,尾部使用分号,空语句块等问题。
代码质量问题:未使用变量、三等号、全局变量声明,v-for会自动追加key值,多单词驼峰来进行组件命名等问题。
三、VsCode如何安装

四、Vscode 如何全局配置

// 全局配置vscode
// 打开:设置 -> 文本编辑器 -> 字体 -> 在 settings.json 中编辑

{
  "prettier.configPath": ".prettierrc.json", // 以项目中.prettierrc.json文件为准
  "editor.codeActionsOnSave": {},
  "window.zoomLevel": 1,
  "editor.wordSeparators": "`~!@#$%^&*()=+[{]}\\|;:'\",.<>/?",
  "js/ts.implicitProjectConfig.checkJs": true,
  "prettier.requireConfig": true,
  "editor.fontLigatures": false // 代码分割去掉了中划线-
}
View Code

六、Vscode如何项目配置 (目录 .vscode/settings.json)

{
  "editor.formatOnSave": true, // 每次保存的时候自动格式化
  "editor.defaultFormatter": "esbenp.prettier-vscode", // 为所有语言设置prettier
  "workbench.iconTheme": "vscode-icons", // 文件小图标
}
View Code

 

七、eslint 配置

1. 安装eslint

npm install vite-plugin-eslint

2. 全局配置eslint插件

// vite.config.js
import eslintPlugin from 'vite-plugin-eslint'

export default defineConfig(({ command, mode, ssrBuild }) => {
    return {
        base: '/',
        plugins: [
            eslintPlugin({
                include: ['src/**/*.vue', 'src/*.js', 'src/*.vue'] // 需要 eslint 校验的文件
            })
        ]
    }
})

 3. eslint 与 搭配使用,还需安装的插件 ( 参考图片 )

npm install @babel/eslint-parser eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue prettier vue-eslint-parser

 4. 新建4个文件(.eslintignore 和 .prettierignore 与 .gitignore 保持一致)

参考以下:

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
build
.lh
yarn.lock

/cypress/videos/
/cypress/screenshots/

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.zip
View Code

 

 5. .eslintrc.js 配置

/** .eslintrc.js
 * 在VSCode中安装ESLint插件,编写过程中检测代码质量
 * ESLint 代码质量校验相关配置
 * 这里使用prettier作为代码格式化工具,用ESLint做代码质检
 * 相关配置使用下面extends扩展先做默认设置
 * 在.prettierrc.js文件中配置好后,格式化规则会以.prettierrc.js作为最终格式,所以不建议在本文件中做代码格式化相关配置
 * 相关prettier配置ESLint会默认加载为代码质检 格式化以prettier为主
 * 在本配置文件中只做代码质量约束规范配置
 */
module.exports = {
    root: true,
    env: {
        browser: true,
        node: true,
        es2021: true
    },
    extends: [
        'eslint:recommended', // 使用推荐的eslint
        'plugin:vue/vue3-recommended', // 使用插件支持vue3
        //1.继承.prettierrc.js文件规则  2.开启rules的 "prettier/prettier": "error"  3.eslint fix的同时执行prettier格式化
        'plugin:prettier/recommended',
        'eslint-config-prettier'
    ],
    parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        ecmaFeatures: {
            modules: true,
            jsx: true
        },
        requireConfigFile: false,
        parser: '@babel/eslint-parser'
    },
    plugins: ['vue', 'prettier'],
    globals: {
        defineProps: 'readonly',
        defineEmits: 'readonly',
        defineExpose: 'readonly',
        withDefaults: 'readonly'
    },
    rules: {
        semi: ['warn', 'never'], // 禁止尾部使用分号
        'no-duplicate-case': 'warn', // 禁止出现重复case
        'no-empty': 'warn', // 禁止出现空语句块
        'no-func-assign': 'warn', // 禁止对Function声明重新赋值
        'no-unreachable': 'warn', // 禁止出现[return|throw]之后的代码块
        'no-else-return': 'warn', // 禁止if语句中return语句之后有else块
        'no-empty-function': 'warn', // 禁止出现空的函数块
        'no-lone-blocks': 'warn', // 禁用不必要的嵌套块
        'no-multi-spaces': 'warn', // 禁止使用多个空格
        'no-redeclare': 'warn', // 禁止多次声明同一变量
        'no-return-assign': 'warn', // 禁止在return语句中使用赋值语句
        'no-return-await': 'warn', // 禁用不必要的[return/await]
        'no-self-compare': 'warn', // 禁止自身比较表达式
        'no-useless-catch': 'warn', // 禁止不必要的catch子句
        'no-useless-return': 'warn', // 禁止不必要的return语句
        'no-multiple-empty-lines': 'warn', // 禁止出现多行空行
        'no-trailing-spaces': 'warn', // 禁止一行结束后面不要有空格
        'no-var': 'warn', // 禁止出现var用let和const代替
        'default-case': 'warn', // 要求switch语句中有default分支
        'no-extra-parens': ['error', 'functions'],
        curly: 0, // 要求所有控制语句使用一致的括号风格
        // '@typescript-eslint/no-var-requires': 'off', // 强制使用 import 且不允许使用 require 设置off关闭检查
        'vue/require-v-for-key': 'off', // 对保留元素检查 vue3中v-for会自动追加key值,所以不用再强制添加key属性,所以不检查key的填写
        'vue/valid-v-for': 'error', // 对于非保留(自定义)元素检查  vue3中v-for会自动追加key值,所以不用再强制添加key属性,所以不检查key的填写
        'no-debugger': 'warn', // 禁止出现debugger
        // 添加组件命名忽略规则 vue官方默认规则是多单词驼峰来进行组件命名
        'vue/multi-word-component-names': 'off',
        'vue/no-v-html': 'off', //去忽略v-html警告。
        'vue/no-unused-components': [2], // 禁止组件已注册但未使用的情况
        'vue/html-end-tags': 2, // html 需要有结束标签,除了自闭合标签
        'vue/html-closing-bracket-spacing': 2, // html 需要有结束标签,除了自闭合标签
        'vue/component-definition-name-casing': 0, // 自定义组件名称 - 驼峰和连字符
        'vue/attribute-hyphenation': 0 // 自定义属性名称 - 驼峰和连字符
    }
}
View Code

6.  .prettierrc.json 配置

{
    "tabWidth": 4,
    "semi": false,
    "singleQuote": true,
    "bracketSameLine": true,
    "printWidth": 200,
    "trailingComma": "none",
    "endOfLine": "auto"
}
View Code

7. 运行项目测试

npm run dev

 8. 代码中写错误案例

// views/name.vue
var name = null

9. 浏览器预览name.vue页面

10. 错误提示