【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
  }
}
相关推荐
Smile_Gently2 小时前
前端:最简单封装nmp插件(组件)过程。
前端·javascript·vue.js·elementui·vue
luckycoke8 小时前
小程序立体轮播
前端·css·小程序
一 乐8 小时前
高校体育场管理系统系统|体育场管理系统小程序设计与实现(源码+数据库+文档)
前端·javascript·数据库·spring boot·高校体育馆系统
懒羊羊我小弟8 小时前
常用Webpack Loader汇总介绍
前端·webpack·node.js
祈澈菇凉9 小时前
ES6模块的异步加载是如何实现的?
前端·javascript·es6
我爱学习_zwj9 小时前
4.从零开始学会Vue--{{组件通信}}
前端·javascript·vue.js·笔记·前端框架
顾比魁9 小时前
XSS盲打:当攻击者“盲狙”管理员
前端·网络安全·xss
黑客老李9 小时前
新手小白如何挖掘cnvd通用漏洞之存储xss漏洞(利用xss钓鱼)
java·运维·服务器·前端·xss
晚风予星9 小时前
简记|LogicFlow自定义BPMN元素节点
前端
Json____10 小时前
使用html css js 开发一个 教育机构前端静态网站模板
前端·css·html·js·前端学习·企业站·教育机构网站