【Web前端】vue3整合eslint约束代码格式

一、整合eslint

整合eslint的两种方式:

  • 在已有项目中整合eslint:

    sh 复制代码
    # 安装eslint及其vue插件即可
    npm i -D eslint eslint-plugin-vue
  • 创建项目时整合eslint:
    提示 是否引入ESLint用于代码质量检测 时选择

    sh 复制代码
    # 创建vue3项目
    npx create-vue
    # 下载项目依赖
    npm i

两种方式任一,最终保证package.json文件中内容如下即可:

json 复制代码
{
  "name": "xxx",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore",
    "format": "prettier --write src/"
  },
  "dependencies": {
    "vue": "^3.4.29",
    ...
  },
  "devDependencies": {
    "@rushstack/eslint-patch": "^1.8.0",
    "@vitejs/plugin-vue": "^5.0.5",
    "@vue/eslint-config-prettier": "^9.0.0",
    "eslint": "^8.57.0",
    "eslint-plugin-vue": "^9.23.0",
    "prettier": "^3.2.5",
    "vite": "^5.3.1",
    ...
  }
}

二、配置eslint

在项目根目录下创建.eslintrc.cjs文件:

以下为配置模板,仅供参考:

js 复制代码
/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution')

module.exports = {
  root: true,
  'extends': [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/eslint-config-prettier/skip-formatting'
  ],
  parserOptions: {
    ecmaVersion: 'latest'
  },
  rules: {
    'eqeqeq': 'warn',  // 要求使用 === 和 !==
    'no-dupe-args': 'error', // 禁止 function 定义中出现重名参数
    'no-dupe-keys': 'error', // 禁止对象字面量中出现重复的 key
    'no-eval': 'error', // 禁用 eval()
    'no-self-compare': 'error', // 禁止自身比较
    'no-self-assign': 'error', // 禁止自我赋值
    'no-unused-vars': 'error',  // 禁止出现未使用过的变量
    'no-const-assign': 'error',  // 禁止修改 const 声明的变量
    'no-func-assign': 'error',  // 禁止对 function 声明重新赋值
    'camelcase': 'error',  // 强制使用骆驼拼写法命名约定
    'no-mixed-spaces-and-tabs': 'error', //禁止混用tab和空格
    'indent': ['warn', 2], //缩进风格这里不做硬性规定,但是产品组内要达成统一
    'quotes': ['warn', 'single'], //要求引号类型 `` ' ''
    'semi': ['error', 'never'], //语句强制分号结尾
    'no-alert': process.env.NODE_ENV === 'production' ? 'warn' : 'off', // 禁用 alert
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', // 禁用 console
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off' // 禁用 debugger
  }
}
相关推荐
Senar3 小时前
如何判断浏览器是否开启硬件加速
前端·javascript·数据可视化
HtwHUAT3 小时前
实验四 Java图形界面与事件处理
开发语言·前端·python
利刃之灵3 小时前
01-初识前端
前端
codingandsleeping3 小时前
一个简易版无缝轮播图的实现思路
前端·javascript·css
天天扭码3 小时前
一分钟解决 | 高频面试算法题——最大子数组之和
前端·算法·面试
全宝4 小时前
🌏【cesium系列】01.vue3+vite集成Cesium
前端·gis·cesium
拉不动的猪4 小时前
简单回顾下插槽透传
前端·javascript·面试
烛阴4 小时前
Fragment Shader--一行代码让屏幕瞬间变黄
前端·webgl
爱吃鱼的锅包肉5 小时前
Flutter路由模块化管理方案
前端·javascript·flutter
风清扬雨5 小时前
Vue3具名插槽用法全解——从零到一的详细指南
前端·javascript·vue.js