优化 Vue3 项目代码规范与格式化:EditorConfig、ESLint 与 Prettier 配置指南

在 Vue3 项目开发中,维持统一且规范的代码风格对于团队协作、代码可读性及可维护性至关重要。借助 EditorConfig、ESLint 和 Prettier 这三款强大工具,我们能够轻松实现代码风格的标准化与自动化检查、修复及格式化。接下来,将逐步详解其配置流程。

一、EditorConfig 配置

1. 插件安装与文件创建

首先,在 VS Code 中安装 EditorConfig for VS Code 插件,它能确保不同编辑器遵循相同的基础编码风格设置。随后,于项目根目录下新建 .editorconfig 文件,加入以下关键配置:

[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
end_of_line = crlf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120

特别留意,若项目运行于非 Windows 系统,应将 end_of_line 设置为 cr,以适配不同操作系统的换行符规范,避免换行不一致导致的潜在问题。

二、ESLint 配置

1. 安装

ESLint 是保障代码质量的核心利器,用于检查语法错误、定位潜在问题并强制推行统一代码风格。执行以下命令安装:

npm i eslint -D

2. 初始化

借助 npm init @eslint/config 命令可交互式地生成适配项目需求的 ESLint 配置文件。以下为详细操作实例:

PS D:\workspace\vue3\weiz-vue3-template> npm init @eslint/config
Need to install the following packages:
@eslint/create-config@0.4.6
Ok to proceed? (y)
# 输入 y 开启安装流程
? How would you like to use ESLint?... # 如何运用 ESLint,选第三项可全方位保障代码质量
  To check syntax only
  To check syntax and find problems
> To check syntax, find problems, and enforce code style 
# 选定此项
? What type of modules does your project use?... # 项目模块类型,选 JavaScript modules (import/export) 适配现代项目结构
> JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these
# 选择此项
? Which framework does your project use?... # 因是 Vue3 项目,选 Vue.js
  React
> Vue.js
  None of these
# 选定 Vue
? Does your project use TypeScript? » No / Yes # 若项目使用 TS,选 Yes
# 按需选择
? Where does your code run?...  (Press <space> to select, <a> to toggle all, <i> to invert selection)
# 代码运行环境,空格选中 Browser 和 Node,涵盖前端与后端运行场景
√ Browser
√ Node
# 确认选择回车
  Use a popular style guide 
> Answer questions about your style # 自定义风格更贴合项目独特需求
# 选此项
? What format do you want your config file to be in?... # 配置文件格式,推荐 JavaScript 方便动态配置
> JavaScript
  YAML
  JSON
# 建议选 JavaScript
? What style of indentation do you use?... # 缩进风格,空格便于阅读与协作
  Tabs
> Spaces
# 选空格
? What quotes do you use for strings?... # 字符串引号,单引号简洁,减少转义字符使用
  Double
> Single
# 选单引号
? What line endings do you use?... # 行尾格式,Windows 系统选 Windows,非 Windows 选 Unix
  Unix
> Windows
# 按需选择
? Do you require semicolons? » No / Yes # 分号需求,依团队习惯,此处选 No
# 做出选择
@typescript-eslint/eslint-plugin@latest eslint-plugin-vue@latest @typescript-eslint/parser@latest eslint@latest
? Would you like to install them now? » No / Yes
# 选 Yes 安装依赖
? Which package manager do you want to use?... # 安装方式选 npm
> npm
  yarn
  pnpm
# 选定后等待安装完成
...
added 138 packages, changed 1 package, and audited 184 packages in 50s
 
39 packages are looking for funding
  run `npm fund` for details
 
found 0 vulnerabilities
Successfully created.eslintrc.cjs file in D:\workspace\vue3\weiz-vue3-template

安装完毕后,根目录会生成 .eslintrc.cjs 文件,内含根据所选配置生成的基础规则。

3. 简易安装

若熟悉 ESLint 依赖构成,后续可直接安装关键依赖包,简化流程:

npm i @typescript-eslint/eslint-plugin@latest eslint-plugin-vue@latest @typescript-eslint/parser@latest eslint@latest -D

然后手动在根目录新建 .eslintrc.cjs,将常用配置内容复制进去,快速搭建基础配置框架。

4. .eslintrc.cjs 配置详解

以下是一份涵盖常见场景的基础配置示例:

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-essential',
    'plugin:prettier/recommended' // 后续用于兼容 Prettier,确保两者协同工作
  ],
  overrides: [
    {
      env: {
        node: true
      },
      files: ['.eslintrc.{js,cjs}'],
      parserOptions: {
        sourceType: 'script'
      }
    }
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    parser: '@typescript-eslint/parser',
    sourceType: 'module'
  },
  plugins: ['@typescript-eslint', 'vue'],
  rules: {
    indent: ['error', 2],
    'linebreak-style': ['error', 'windows'],
    quotes: ['error', 'single'],
    semi: ['error', 'never']
  }
}

此配置设定了代码运行环境变量、继承一系列推荐规则集、指定解析器及插件,并定义了核心代码风格规则,如缩进为 2 个空格、行尾格式(Windows 系统)、单引号及省略分号等。

5. .eslintignore 文件

在根目录创建 .eslintignore 文件,罗列无需 ESLint 检查的文件与目录,提升检查效率,避免对第三方库或生成文件的不必要校验:

node_modules
dist
public
*.md
*.txt
.vscode
index.html

6. 增加命令至 package.json

修改 package.json 文件,新增 lint 命令:

"scripts": {
  "lint": "eslint --fix --ext.ts,.tsx,.vue,.js,.jsx --max-warnings 0"
}

运行 npm run lint,ESLint 会自动修复可修复的代码问题,助力维持代码规范性。

三、Prettier 配置

1. 安装

Prettier 专注于代码格式化,安装简便,执行:

npm i prettier eslint-config-prettier eslint-plugin-prettier -D

后两个依赖用于化解 Prettier 与 ESLint 潜在冲突,确保两者和谐共存。

2. .prettierrc 配置

于根目录新建 .prettierrc 文件,填入以下配置:

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 120,
  "singleQuote": true,
  "trailingComma": "none",
  "bracketSpacing": true,
  "semi": false,
  "endOfLine": "crlf"
}

注意,若项目部署于非 Windows 系统,将 endOfLine 设为 cr,适配系统换行特性。

3. .prettierignore 文件

同样在根目录创建 .prettierignore 文件,指定无需 Prettier 格式化的文件与目录,与 .eslintignore 类似,减少不必要操作:

node_modules
dist
public
*.md
*.txt
.vscode
index.html

四、总结

完成上述一系列精心配置后,编码效率将大幅跃升。运行 npm run lint 能自动修复多数代码格式瑕疵,保障代码符合既定规范;或者在编辑器中右键选择 Prettier 格式化代码,实时美化代码呈现。这两款工具携手,从代码检查到格式化全方位护航,让代码始终保持整洁、规范,无论是团队协作还是后续维护都更加得心应手。

愿这份详尽指南助力您打造高质量、风格统一的 Vue3 项目代码库,开启高效开发之旅。

最后修改:2024 年 12 月 11 日
如果觉得我的文章对你有用,请随意赞赏