2025-12-20 vue3中 eslint9+和prettier配置

eslint 9+相较8版本使用eslint.config.js和扁平化配置方式。

1.在项目根目录下安装所需的开发依赖包

shell 复制代码
# 核心代码检查与格式化工具
pnpm add -D eslint prettier

# Vue.js 语法支持
pnpm add -D eslint-plugin-vue

# Prettier 与 ESLint 集成
pnpm add -D eslint-config-prettier eslint-plugin-prettier

💅 2. prettier配置

vscode中安装插件

根目录下新建配置文件 .prettierrc

js 复制代码
{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 100,
  "arrowParens": "avoid",
  "htmlWhitespaceSensitivity": "ignore"
}

3.eslint配置并将prettier规则作为eslint一部分,对不符合要求的报错

js 复制代码
// eslint.config.js
import eslintPluginVue from 'eslint-plugin-vue'
import vueEslintParser from 'vue-eslint-parser'
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'
// console.log(eslintPluginPrettierRecommended)
export default [
  // 全局配置:指定环境、解析器选项
  {
    files: ['**/*.js', '**/*.vue'],
    ignores: ['vite.config.js', 'node_modules/', 'dist/', 'public/'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      globals: {
        browser: true, // 浏览器环境全局变量
        node: true, // Node.js 环境全局变量
        es2021: true // ES2021 语法支持
      }
    },
    rules: {
      'no-console': 'warn',
      'no-debugger': 'error',
      'no-unused-vars': ['warn', { varsIgnorePattern: '^_' }]
    }
  },

  // Vue 单文件组件专属配置
  {
    files: ['**/*.vue'],
    // 使用 vue-eslint-parser 解析 .vue 文件
    languageOptions: {
      parser: vueEslintParser,
      parserOptions: {
        parser: 'espree', // 解析 <script> 块内的 JavaScript
        ecmaVersion: 'latest',
        sourceType: 'module'
      }
    },
    plugins: {
      vue: eslintPluginVue
    },
    rules: {
      // 启用 Vue 官方推荐规则
      ...eslintPluginVue.configs['flat/recommended'].rules,
      // 自定义 Vue 规则
      'vue/multi-word-component-names': 'off' // 关闭组件名必须多单词的要求
    }
  },
  //prettier配置
  eslintPluginPrettierRecommended
]

此时运行

shell 复制代码
npm run lint

可以对不符合规则的代码检查,包含不符合eslint规则的

4.配置vscode插件eslintPrettier ESlint,设置默认格式化工具为Prettier ESlint,让eslint直接报错prettier中的配置,有时修改了.prettierrc中的配置需要重启Prettier ESlint插件才能生效。

对于.eslintignore文件缺失时eslint会使用.gitignore文件

相关推荐
code_YuJun2 小时前
脚手架开发工具——判断文件是否存在 path-exists
前端
code_YuJun2 小时前
脚手架开发工具——root-check
前端
用户54277848515402 小时前
XMLHttpRequest、AJAX、Fetch 与 Axios
前端
打小就很皮...2 小时前
React 实现富文本(使用篇&Next.js)
前端·react.js·富文本·next.js
智算菩萨3 小时前
实战:高级中文自然语言处理系统的Python设计与实现
前端·javascript·easyui
远山无期3 小时前
解决Tailwind任意值滥用:规范化CSS开发体验
前端·css·eslint
用户54277848515403 小时前
Vue 3 中开发高阶组件(HOC)与 Renderless 组件
前端
HIT_Weston3 小时前
67、【Ubuntu】【Hugo】搭建私人博客(一)
前端·ubuntu·hugo
阿里巴啦4 小时前
用React+Three.js 做 3D Web版搭建三维交互场景:模型的可视化摆放与轻量交互
前端·react·three.js·模型可视化·web三维·web三维交互场景