Vue3 + ESLint9代码规范配置指南

 更新时间:2026年05月24日 09:32:21   作者:叫我少年  
在Vue3项目中引入ESLint不仅能提升代码美观度,通过eslint-plugin-vueue插件,以及扁平配置方式,实现高效统一的代码风格检查,具有一定的参考价值,感兴趣的可以了解一下

在 Vue 3 项目里引入 ESLint,不只是为了“看着舒服”——它能帮你提前揪出潜在 bug,统一团队的代码风格,避免因为缩进、引号这类。关键插件是 eslint-plugin-vue,它专门为 Vue 文件提供了针对性规则。

参考ESLint v9 官方文档

开始之前:装包与初始化

一行命令搞定依赖:

# 安装 ESLint 核心库
npm install --save-dev eslint
# 交互式生成配置文件
npx eslint --init

初始化过程会问一些问题(比如你用的是哪种模块格式、框架、TypeScript 还是 JS 等),一路按项目需求选就行。

配置脚本:写入package.json

把下面这段加进 scripts​ 里,日常敲 npm run lint​ 就能检查所有 .js​、.ts​、.vue 文件:

"scripts": {
  "dev": "vite",
  "build": "vue-tsc -b && vite build",
  "preview": "vite preview",
  "lint": "eslint . --ext .js,.ts,.vue",
  "lint:fix": "eslint . --ext .js,.ts,.vue --fix",
  "lint:src": "eslint src --ext .js,.ts,.vue",
  "lint:typescript": "eslint . --ext .ts,.vue",
  "lint:report": "eslint . --ext .js,.ts,.vue --format html > eslint-report.html",
  "precommit": "lint-staged"
}

常见坑​:如果你用 pnpm,别忘了装 lint-staged​ 和 husky​,否则 precommit 脚本不会生效。

配置文件:eslint.config.ts(ESLint 9 风格)

ESLint 9 全面拥抱扁平配置(flat config),不再用 .eslintrc.js。以下是一个适配 Vue 3 + TypeScript 的示例:

import js from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint';
import pluginVue from 'eslint-plugin-vue';
import { defineConfig } from 'eslint/config';
export default defineConfig([
  {
    ignores: [
      'node_modules',
      'dist',
      '.gitignore',
      'package.json',
      'package-lock.json',
      '.DS_Store',
      'dev-dist',
      'dist_electron',
      '*.d.ts',
      'src/assets/**'
    ],
    files: ['**/*.{js,mjs,cjs,ts,mts,cts,vue}'],
    plugins: { js },
    extends: ['js/recommended'],
    languageOptions: { globals: globals.browser }
  },
  { files: ['**/*.js'], languageOptions: { sourceType: 'commonjs' } },
  /** js推荐配置 */
  tseslint.configs.recommended,
  /** vue推荐配置 */
  pluginVue.configs['flat/essential'],
  { files: ['**/*.vue'], languageOptions: { parserOptions: { parser: tseslint.parser } } }
]);

划重点pluginVue.configs['flat/essential']​ 是 ESLint 9 下 eslint-plugin-vue​ 的推荐入口。如果你需要更强的规则(如 strongly-recommended​),可以改为 flat/strongly-recommended

到此这篇关于Vue3 + ESLint9代码规范配置指南的文章就介绍到这了,更多相关Vue3  ESLint9代码规范内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!‍

相关文章

最新评论