【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
  }
}
相关推荐
Csvn3 小时前
Monorepo 迁移血泪史:从 Multi-Repo 到 Turborepo,这 3 个坑我帮你踩完了
前端
星栈3 小时前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架
用户987409238873 小时前
用 Remotion + edge-tts 打造中文教学视频全自动流水线
前端
风骏时光牛马3 小时前
Less前端工程化实战:变量混合器与项目样式分层落地
前端
假如让我当三天老蒯3 小时前
Options API(选项式 API) 和 Composition API(组合式 API)
前端·vue.js·面试
SameX3 小时前
iOS 独立开发实践:用 MapKit + 像素渲染实现 Citywalk 轨迹地图 App「雁过留痕」
前端
skyey3 小时前
页面加载时,深色模式闪白的问题解决
前端
IT_陈寒3 小时前
Java 并行流把我坑惨了,这6小时加班值了
前端·人工智能·后端
anOnion13 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户479492835691513 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端