【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
  }
}
相关推荐
东方小月5 小时前
从零开发一个 Coding Agent(四):使用状态机校验大模型事件流
前端·人工智能·后端
Csvn5 小时前
🧩 ESM vs CJS 混用的 7 个「天坑」——从 TypeScript 编译到 Node 与浏览器
前端
Csvn5 小时前
🎯 Web 性能 API 集合:Performance Observer 的 5 个冷门妙用
前端
Csvn5 小时前
深入 React 闭包陷阱:从根源上理解并根治 stale closure
前端
whyfail5 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
用户059540174466 小时前
LangChain 记忆测试踩坑实录:这两个坑让我排查了 4 小时
前端·css
程序员黑豆6 小时前
鸿蒙应用开发:@Monitor 装饰器使用教程
前端·harmonyos
SamChan907 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
kyriewen7 小时前
AI Agent 9秒删光了生产数据库——我给自己的项目做了5个紧急检查
前端·ai编程·claude
IT_陈寒7 小时前
JavaScript的this又双叒叕让我怀疑人生了
前端·人工智能·后端