从零开始创建一个vue3+vite项目并集成element-plus、eslint以及prettier

192 阅读6分钟

项目git地址, 欢迎修改提交,不足地方还请补充批评指正!

项目git地址

简介

ESLint 是一个用于识别和报告在 ECMAScript/JavaScript 代码中发现的模式的工具,其目标是使代码更加一致并避免错误。

ESLint 是完全插件化的。每条规则都是一个插件,你可以在运行时添加更多。你还可以添加社区插件、配置和解析器来扩展 ESLint 的功能。

先决条件

要使用 ESLint,你必须安装并构建 Node.js^18.18.0^20.9.0>=21.1.0)并支持 SSL。(如果你使用的是官方 Node.js 发行版,则始终内置 SSL。)

快速安装

新建一个vue3-vite项目

image-20240402090448932

npm init @eslint/config

image-20240402090403340

image-20240402085716956

如果你正在使用 ESLint 8.23.x 和 WebStorm 2022.2.x 或 PhpStorm 2022.2.x。 那么你可能会遇到 TypeError: this.libOptions.parse is not a function。 这是 ESLint 8.23.x 中的一个bug。ESLint 团队正在努力解决这个问题,希望很快就能解决。 在此之前,解决方法是将你的 ESLint 的版本降至8.22。

首先安装依赖

安装在devDependencies里作为开发依赖,后缀加-D

"eslint": "8.22.0",
"eslint-plugin-auto-import": "^0.1.1",
"eslint-plugin-vue": "^9.23.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-config-prettier": "^9.1.0",
"prettier": "^3.2.5",
npm i eslint@8.22.0 -D

后创建 .eslintignore 文件, 排除不必要的格式化目录

build/*.js
src/assets
public
dist
node_modules

.eslintrc.js

语法规则

规则严重性

要更改规则的严重性,请将规则 ID 设置为以下值之一:

  • "off"0 - 关闭规则
  • "warn"1 - 打开规则作为警告(不影响退出代码)
  • "error"2 - 打开规则作为错误(触发时退出代码为 1)

其中如果使用 extends:eslint:recommended ,会使用eslint推荐的规则,就不用手动打开,但会触发error需要关闭就对应规则off

规则参考 eslint.nodejs.cn/docs/latest… .eslintrc.js文件

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:prettier/recommended',
    'plugin:vue/vue3-essential',
    'eslint-config-prettier',
    // './.eslintrc-auto-import.json'
  ],
  overrides: [
    {
      env: {
        node: true,
      },
      files: [
        '.eslintrc.{js,cjs}',
      ],
      parserOptions: {
        sourceType: 'script',
      },
    },
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [
    'vue',
    'prettier'
  ],
  rules: {
    semi: ['warn', 'never'], // 禁止尾部使用分号
    'no-undef': 'warn', //禁止使用未声明的变量
    'no-unused-vars': 'warn', //禁止未使用的变量
    'linebreak-style': ['off'], // 关闭换行符验证
    'no-duplicate-case': 'warn', // 禁止出现重复case
    'no-empty': 'warn', // 禁止出现空语句块
    'no-eval': 'error',
    'no-var': 'error',
    'no-with': 'error',
    'no-use-before-define': 'warn', //禁止在定义变量之前使用变量
    'no-func-assign': 'warn', // 禁止对Function声明重新赋值
    'no-unreachable': 'warn', // 禁止出现[return|throw]之后的代码块
    'no-else-return': 'warn', // 禁止if语句中return语句之后有else块
    '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-mixed-spaces-and-tabs': 'warn', // 禁止空格和tab的混合缩进
    'no-multiple-empty-lines': 'warn', // 禁止出现多行空行
    'no-trailing-spaces': 'warn', // 禁止一行结束后面不要有空格
    'no-useless-call': 'warn', // 禁止不必要的.call()和.apply()
    'no-delete-var': 'off', // 允许出现delete变量的使用
    'no-shadow': 'off', // 允许变量声明与外层作用域的变量同名
    'dot-notation': 'warn', // 要求尽可能地使用点号
    'default-case': 'warn', // 要求switch语句中有default分支
    eqeqeq: 'warn', // 要求使用 === 和 !==
    curly: 'off', // 要求所有控制语句使用一致的括号风格
    'space-before-blocks': 'warn', // 要求在块之前使用一致的空格
    'space-in-parens': 'warn', // 要求在圆括号内使用一致的空格
    'space-infix-ops': 'warn', // 要求操作符周围有空格
    'space-unary-ops': 'warn', // 要求在一元操作符前后使用一致的空格
    'switch-colon-spacing': 'warn', // 要求在switch的冒号左右有空格
    'arrow-spacing': 'warn', // 要求箭头函数的箭头前后使用一致的空格
    'array-bracket-spacing': 'warn', // 要求数组方括号中使用一致的空格
    'brace-style': 'warn', // 要求在代码块中使用一致的大括号风格
    'no-empty-function': 'warn', //空方法警告
    camelcase: 'off', // 要求使用骆驼拼写法命名约定
    indent: ['warn', 2, { SwitchCase: 1 }], // 要求使用JS一致缩进2个空格
    'max-depth': ['warn', 4], // 要求可嵌套的块的最大深度4
    'max-statements': ['warn', 100], // 要求函数块最多允许的的语句数量20
    'max-statements-per-line': ['warn', { max: 1 }], // 要求每一行中所允许的最大语句数量
    'vue/no-v-html': 'warn', // xss警告
  }
};

代码格式化工具,安装以下依赖,安装时注意加 -D选项安装在devDependencies中

    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-prettier": "^5.1.3",
    "prettier": "^3.2.5",

然后在eslintrc.js中配置插件

  plugins: [
    'vue',
    'prettier'
  ],
   extends: [
    'eslint:recommended', //使用eslint推荐的配置
    'plugin:prettier/recommended', // prettier推荐的
    'plugin:vue/vue3-essential', //vue3推荐插件
    'eslint-config-prettier', 
    './.eslintrc-auto-import.json' //自动导入配置文件
  ],

.prettierrc

格式化规则

{
  "tabWidth": 2, //缩进字节数
  "semi": false, // 禁用分号
  "trailingComma": "none", //对象或数组最后不加逗号
  "singleQuote": true, //使用单引号
  "printWidth": 120,
  "endOfLine": "auto"
}

然后在package.json中配置Lint命令

image-20240321103556872

重启编辑器

可以在webStorm中设置保存时自定eslint --fix 来帮助我们在保存时自动修复问题

image-20240403134533910

自动导入插件

编写项目时重复大量的插件和方法需要每次import比较繁琐,例如vue的相关响应式ref,reactive,生命周期,element-plus相关函数组件等

安装下述三个依赖在dev

    "eslint-plugin-auto-import": "^0.1.1",
    "unplugin-auto-import": "^0.17.5",
    "unplugin-vue-components": "^0.26.0",

在根目录上配置自动导入的方法

文件名 eslintrc-auto-import.json

{
  "globals": {
    "computed": true,
    "createApp": true,
    "customRef": true,
    "defineAsyncComponent": true,
    "defineComponent": true,
    "effectScope": true,
    "EffectScope": true,
    "getCurrentInstance": true,
    "getCurrentScope": true,
    "h": true,
    "inject": true,
    "isReadonly": true,
    "isRef": true,
    "markRaw": true,
    "nextTick": true,
    "onActivated": true,
    "onBeforeMount": true,
    "onBeforeUnmount": true,
    "onBeforeUpdate": true,
    "onDeactivated": true,
    "onErrorCaptured": true,
    "onMounted": true,
    "onRenderTracked": true,
    "onRenderTriggered": true,
    "onScopeDispose": true,
    "onServerPrefetch": true,
    "onUnmounted": true,
    "onUpdated": true,
    "provide": true,
    "reactive": true,
    "readonly": true,
    "ref": true,
    "resolveComponent": true,
    "shallowReactive": true,
    "shallowReadonly": true,
    "shallowRef": true,
    "toRaw": true,
    "toRef": true,
    "toRefs": true,
    "triggerRef": true,
    "unref": true,
    "useAttrs": true,
    "useCssModule": true,
    "useCssVars": true,
    "useRoute": true,
    "useRouter": true,
    "useSlots": true,
    "useStore": true,
    "watch": true,
    "watchEffect": true
  }
}

并且在vite.config.js中配置插件

import autoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
  plugins: [
    vue(),
    autoImport({
      imports: ['vue', 'vue-router', 'pinia'],
      // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
      // 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式)
      resolvers: [
        ElementPlusResolver()

        // Auto import icon components
        // 自动导入图标组件
        // IconsResolver()
      ]
    })
  ]
})

这样无需在main.js中配置全局变量,组建中可以直接使用vue全家桶和elment-plus相关方法,非常好用,

JS中大大简洁

image-20240403143250041

加入jsconfig.json

在引入组件时正确解析@符号后的路径,点击组件可以正确跳转

{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "baseUrl": "./",
    "moduleResolution": "node",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "exclude": ["node_modules"]
}

并且在vite.config.js中配置

import path from 'path'


resolve: {
    // https://cn.vitejs.dev/config/#resolve-alias
    alias: {
      // 设置路径
      '~': path.resolve(__dirname, './'),
      // 设置别名
      '@': path.resolve(__dirname, './src')
    },
    // https://cn.vitejs.dev/config/#resolve-extensions
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  },