【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
  }
}
相关推荐
OpenTiny社区32 分钟前
Coding Agent 到底是怎么工作的,它又为什么会在复杂代码库里失真?
前端·github·agent
奇奇怪怪的37 分钟前
Graph RAG:知识图谱增强检索
前端
默_笙1 小时前
🌏 MCP 是 AI 界的 USB-C:一个协议让所有模型都能用上所有工具
前端·javascript
以和为贵1 小时前
🔥前端也能搞懂流式输出:从 SSE 到打字机效果
前端·人工智能·架构
阿成学长_Cain2 小时前
Linux telinit 命令详解:运行级别切换|关机重启|系统维护一站式掌握
linux·运维·前端·网络
Patrick_Wilson2 小时前
最佳实践是有保质期的:从一次 CDN external 白屏事故说起
前端·性能优化·前端工程化
YHHLAI2 小时前
[特殊字符] Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·人工智能
nuIl3 小时前
我把 5 个编码 Agent 塞进了一个 npm 包
前端·agent·claude
L-影3 小时前
FastAPI 静态文件:Web 页面的“固定展柜”与“加速引擎”
前端·fastapi
陪我去看海3 小时前
受够了 AI 写完代码留下一堆端口?我做了一个端口管理App!
前端·macos·vibecoding