欢迎光临
我们一直在努力

vite+vue3+ts前端搭建与配置(5) -代码检查

代码风格与格式化

工具名称功能定位主要用途
ESLint / ESLint 中文网 代码质量与风格检查 检查代码中的潜在错误、不规范写法,提供代码质量保障。
prettier / Prettier 中文网 代码格式化 统一代码外观,解决团队协作中的格式争议(如缩进、引号、尾随逗号等)。
Stylelint 样式文件质量与风格检查 检查 CSS、SCSS、Less 等样式文件中的问题,强制执行一致的样式编码规范。

ESLint

1. 安装

npm init @eslint/config@latest
# or
pnpm create @eslint/config@latest

D:\\vue-admin-main>pnpm create @eslint/config@latest
@eslint/create-config: v1.10.0

√ What do you want to lint? · javascript
√ How would you like to use ESLint? · problems
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser, node
√ Which language do you want your configuration file be written in? · ts
Jiti is required for Node.js <24.3.0 to read TypeScript configuration files.
√ Would you like to add Jiti as a devDependency? · No / Yes
The config that you've selected requires the following dependencies:

eslint, @eslint/js, globals, typescript-eslint, eslint-plugin-vue, jiti
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · pnpm
☕️Installing...

安装成功后,会生成文件 eslint.config.ts:

Tips:从 ESLint v9 开始,推荐使用新的扁平化配置文件格式,即 eslint.config.js 或 eslint.config.ts。这种新格式提供了更灵活和模块化的配置方式。如果项目中两者同时存在,ESLint 会优先使用 eslint.config.ts。

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([
{
files: ['**/*.{js,mjs,cjs,ts,mts,cts,vue}'],
plugins: { js },
extends: ['js/recommended'],
languageOptions: { globals: { …globals.browser, …globals.node } },
},
tseslint.configs.recommended,
pluginVue.configs['flat/essential'],
{
files: ['**/*.vue'],
languageOptions: { parserOptions: { parser: tseslint.parser } },
},
])

2. 添加 Eslint 脚本

在 package.json 中添加 Eslint 脚本:

"scripts": {
"lint:eslint": "eslint –cache –max-warnings 0 \\"{src,mock}/**/*.{vue,ts,tsx}\\" –fix"
},

该命令会自动修复符合 ESLint 规则的代码问题,并输出检查结果。

3. 定制化配置

此配置是基于项目中使用了 vue3 和 TypeScript,需要在默认配置上调整,同时要解决集成Prettier时的冲突问题。

要安装的必要依赖:

插件名称功能描述
eslint-config-prettier 它关闭了所有可能和 Prettier 冲突的 ESLint 规则
eslint-plugin-prettier 将 Prettier 作为 ESLint 规则进行检测,任何由 Prettier 发现的格式问题都会被视为 ESLint 的问题
eslint-plugin-vue 提供 Vue 相关的 ESLint 规则 (这个库在安装eslint时已经选择了安装)
vue-eslint-parser 允许 ESLint 使用 Vue 的解析器

安装:npm i -D eslint-config-prettier eslint-plugin-prettier vue-eslint-parser 若安装 eslint 没有安装eslint-plugin-vue则需要安装:npm i -D eslint-plugin-vue

完整的配置文件eslint.config.ts:

import js from '@eslint/js' // JavaScript 规则
import globals from 'globals'
import tseslint from 'typescript-eslint' // TypeScript 规则
import pluginVue from 'eslint-plugin-vue' // Vue 规则
import { defineConfig } from 'eslint/config'
import vueParser from 'vue-eslint-parser' // Vue 解析器
// https://github.com/prettier/eslint-config-prettier?tab=readme-ov-file#installation
import eslintConfigPrettier from 'eslint-config-prettier/flat' // 禁用与 Prettier 冲突的规则
// https://github.com/prettier/eslint-plugin-prettier
import eslintPluginPrettier from 'eslint-plugin-prettier/recommended' // 运行 Prettier 规则

/** @type {import('eslint').Linter.FlatConfig[]} */
export default defineConfig([
// ========== 基础配置 ==========
{
// 指定检查的文件类型
files: ['**/*.{js,mjs,cjs,ts,mts,cts,vue}'],
// 忽略的文件
ignores: [
'**/*.d.ts', // TypeScript 声明文件
'dist/**', // 构建输出目录
'node_modules/**', // 依赖目录
'public/**', // 静态资源目录
'**/__tests__/**', // 测试目录
'**/__mocks__/**', // mock 目录
],
// 设置全局变量
languageOptions: {
globals: {
…globals.browser,
…globals.node,
// 添加自定义的类型
// PageQuery: "readonly"
},
},
},

// ========== JavaScript 配置 ==========
js.configs.recommended,

// ========== TypeScript 配置 ==========
tseslint.configs.recommended, // TypeScript 推荐规则
{
ignores: ['**/*.d.ts'], // 排除d.ts文件
languageOptions: {
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: __dirname,
},
},
// TypeScript 特定规则覆盖
rules: {
'@typescript-eslint/no-explicit-any': 'warn', // 允许使用 any 但给出警告
'@typescript-eslint/no-empty-function': 'off', // 允许空函数
'@typescript-eslint/no-empty-object-type': 'off', // 允许空对象类型
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_', // 忽略以 _ 开头的变量未使用警告
varsIgnorePattern: '^[A-Z0-9_]+$', // 忽略变量名为大写字母、数字或下划线组合的未使用警告(枚举定义未使用场景)
ignoreRestSiblings: true, // 忽略解构赋值中同级未使用变量的警告
},
],
},
},

// ========== Vue 配置 ==========
pluginVue.configs['flat/essential'],
{
files: ['**/*.vue'],
// Vue 文件解析器配置
languageOptions: {
parser: vueParser,
parserOptions: {
parser: tseslint.parser, // 使用 TypeScript 解析器解析 <script> 部分
extraFileExtensions: ['.vue'], // 指定额外文件扩展名
ecmaVersion: 'latest', // 使用最新的 ECMAScript 版本
sourceType: 'module', // 使用 ES 模块
},
},
rules: {
// Vue 特定规则覆盖
'vue/multi-word-component-names': 'off', // 允许单个单词组件名
'vue/no-v-html': 'warn', // 允许使用 v-html 但给出警告
'vue/require-default-prop': 'off', // 不要求必须提供默认 prop
},
},

// ========== 项目自定义规则 ==========
{
// 通用规则覆盖
rules: {
'no-alert': 'error', // 禁止使用 alert
'no-undef': 'error', // 禁止未声明的变量
'no-unreachable': 'error', // 禁止不可达代码
'no-var': 'error', // 禁止使用 var
'prefer-const': 'error', // 优先使用 const
eqeqeq: ['error', 'always'], // 强制使用 === 和 !==
curly: ['error', 'multi-line'], // 强制大括号风格
},
},

// ========== Prettier 集成 (Prettier 配置应该严格位于最后)==========
// 禁用与 Prettier 冲突的规则
eslintConfigPrettier,
// 应用 Prettier 规则
eslintPluginPrettier,
])

4. ESlint配置到Vite

vite-plugin-eslint2的作用是,在开发阶段,ESLint 会在保存代码的时候,自动检查代码,并给出相应的提示。

安装 npm install vite-plugin-eslint2 -D

修改 vite.config.js 配置:

import viteEslint from 'vite-plugin-eslint2';

plugins: [viteEslint()]

再重启项目,即可在命令窗口看到ESlint错误信息

Prettier

通常 ESlint 只负责代码的风格检查并给出提示,配合Prettier对代码进行格式化

1. 安装

pnpm add –save-dev –save-exact prettier
# or
npm install –save-dev –save-exact prettier

2. 配置.prettierrc.js

创建.prettierrc.js文件并添加配置:

/**
* 更多配置请查看:
* 中文网 https://prettier.nodejs.cn/docs/options
* 官网 https://prettier.io/docs/options
*/

export default {
// 设置每行代码的最大宽度
printWidth: 100,
// 设置每个tab键对应的空格数为2。
tabWidth: 2,
// 是否使用tab键缩进,默认为false,表示使用空格缩进。
useTabs: false,
// 是否在语句末尾添加分号。
semi: true,
// 是否对Vue文件中的script和style标签进行缩进。
vueIndentScriptAndStyle: true,
// 每个属性独占一行
singleAttributePerLine: true,
// 是否使用单引号代替双引号。
singleQuote: false,
// 在对象或数组最后一个元素后是否添加逗号(符合 ES5 标准)
trailingComma: 'es5',
// 在对象字面量中打印括号之间的空格。
bracketSpacing: true,
// 箭头函数参数只有一个时是否省略括号
arrowParens: 'always',
// 是否在文件顶部插入Pragma标记。
insertPragma: false,
// 换行符的样式,"auto"表示根据操作系统自动选择。
endOfLine: 'auto',
}

3. 添加.prettierignore忽略文件

指定 Prettier 不需要格式化的文件和文件夹

# Ignore artifacts:

node_modules
dist
public

.local
.output.js

**/*.svg
**/*.sh

4. 添加 Prettier 脚本

在 package.json 中添加 Prettier 脚本:

"scripts": {
"lint:prettier": "prettier –write ."
}

运行npm run lint:prettier会对所有文件进行格式化。

或者使用:npx prettier . –check 它只检查文件是否已格式化,而不是覆盖它们。

Stylelint

Stylelint主要用于强制执行一致的 CSS 编码规范,避免样式错误并提升代码质量

推荐使用 Stylelint 的情况:

  • 项目中有大量自定义 CSS/SCSS 代码(不只是实用类)
  • 需要强制执行一致的 CSS 编写规范
  • 需要检查 CSS 选择器命名规范
  • 需要检查 CSS 属性顺序

若项目中几乎完全使用 Tailwind/Unocss 实用类(很少自定义 CSS)想减少配置复杂度,则不需要使用 Stylelint。

1. 安装

npm install -D postcss postcss-html postcss-scss stylelint stylelint-config-recommended stylelint-config-recommended-scss stylelint-config-recommended-vue stylelint-config-recess-order stylelint-config-html stylelint-prettier

依赖库描述备注
stylelint 强大的 CSS linter(检查器) Stylelint 地址
stylelint-config-recommended 官方推荐的基础规则集(仅检查潜在错误,不包含风格约束) 与 stylelint-config-standard(严格(170+ 规则)) 相比,此配置更灵活更宽松(60+ 规则,仅必要检查)
stylelint-config-recommended-scss 为 SCSS/Sass 扩展的推荐规则(变量、混合等语法检查)
stylelint-config-recommended-vue Vue 单文件组件样式检查的推荐规则
stylelint-config-html 检查 HTML 内联样式 –
stylelint-config-recess-order 按照属性类型分组排序(如布局 → 尺寸 → 颜色,类似 Recess 规范) –
postcss CSS 解析工具,允许使用现代 CSS 语法并将其转换为兼容的旧语法 Stylelint 底层依赖
postcss-html 解析 HTML (类似 HTML) 的 PostCSS 语法 –
postcss-scss 解析 SCSS/Sass 语法(不检查规则,仅提供语法解析支持) –
stylelint-prettier 统一代码风格,格式冲突时以 Prettier 规则为准 需配合 eslint-config-prettier 使用

使用stylelint-config-recommended替代``stylelint-config-standard: stylelint-config-standard官方标准规则(包含 170+ 规则)有着严格的标准规则集(检查错误 + 代码风格),stylelint-config-recommended` 默认包含的规则较少(60+ 规则)仅做基础错误检查,代码风格由自己配置。

tips: 从 Stylelint v15 开始,所有与样式相关的规则均已弃用。如果使用的是 v15 或更高版本,并且未使用这些弃用的规则,则不再需要stylelint-config-prettier插件。

2. 配置stylelint.config.js

export default {
// 继承一系列规则集合,包括标准配置和特定语言的配置
extends: [
"stylelint-config-recommended",
"stylelint-config-recommended-scss",
"stylelint-config-recommended-vue/scss",
"stylelint-config-html/vue",
"stylelint-config-recess-order"
],

plugins: [
"stylelint-prettier",
],

overrides: [
{
"files": ["**/*.{vue,html}"],
"customSyntax": "postcss-html"
},
{
"files": ["**/*.{css,scss}"],
"customSyntax": "postcss-scss"
}
],

/**
* 自定义规则配置。
* – null 表示关闭该规则。
* – always 表示必须遵循该规则。
*/

rules: {
"import-notation": "string",
"selector-class-pattern": null,
"custom-property-pattern": null,
"keyframes-name-pattern": null,
"no-descending-specificity": null,
"no-empty-source": null,
"selector-pseudo-class-no-unknown": [
true,
{
"ignorePseudoClasses": ["global", "export", "deep"]
}
],
"unit-no-unknown": [true, {
"ignoreUnits": ["rpx"]
}],
"property-no-unknown": [
true,
{
"ignoreProperties": []
}
],
"at-rule-no-unknown": [
true,
{
"ignoreAtRules": ["apply", "use", "forward"]
}
]
},

// 忽略的文件类型,避免对非样式文件进行检查
ignoreFiles: [
"**/*.js",
"**/*.jsx",
"**/*.tsx",
"**/*.ts",
"dist",
"public",
"node_modules"
],
};

3. 添加 stylelint 脚本

在 package.json 中添加 stylelint 脚本:

"scripts": {
"lint:style": "stylelint \\"**/*.{vue,css,less,scss}\\" –fix"
}

  • –cache:启用缓存机制,只检查自上次运行后已修改的文件,提高执行效率;
  • –fix:自动修复可修复的代码规范问题(如格式问题);
  • 运行 npm run lint:style 命令,检查样式文件。

VSCode工作区配置

在项目的根目录下创建 .vscode 文件夹,并添加 .vscode/settings.json 文件。 添加以下配置:用于(Eslint、Prettier、Stylelint)保存自动修复。

{
"editor.tabSize": 2,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
// 配置编辑器在哪些上下文显示快速建议(其他区域/注释/字符串内)
"editor.quickSuggestions": {
"other": true,
"comments": true,
"strings": true
},
// 配置保存时自动执行的代码操作(显式启用各类修复)
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.fixAll.eslint": "explicit",
"source.fixAll.stylelint": "explicit"
},
"files.eol": "\\n",
// 定义全局搜索时排除的文件和目录模式
"search.exclude": {
"**/node_modules": true,
"**/*.log": true,
"**/*.log*": true,
"**/bower_components": true,
"**/dist": true,
"**/elehukouben": true,
"**/.git": true,
"**/.gitignore": true,
"**/.svn": true,
"**/.DS_Store": true,
"**/.idea": true,
"**/.vscode": false,
"**/yarn.lock": true,
"**/tmp": true,
"out": true,
"dist": true,
"node_modules": true,
"CHANGELOG.md": true,
"examples": true,
"res": true,
"screenshots": true,
"yarn-error.log": true,
"**/.yarn": true
},
// 配置文件资源管理器中隐藏的文件和目录
"files.exclude": {
"**/.cache": true,
"**/.editorconfig": true,
"**/.eslintcache": true,
"**/bower_components": true,
"**/.idea": true,
"**/tmp": true,
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
},
// 优化文件监视性能的排除规则
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/.vscode/**": true,
"**/node_modules/**": true,
"**/tmp/**": true,
"**/bower_components/**": true,
"**/dist/**": true,
"**/yarn.lock": true
},
"scss.lint.unknownAtRules": "ignore"
}

配置 EditorConfig

主要用于统一不同 IDE 编辑器的编码风格。官方网站: https://editorconfig.org/

VSCode 搜索 EditorConfig for VS Code 找到插件并安装

与现有工具的协调建议

  • 确保 Prettier 配置与 EditorConfig 一致:

    • 缩进类型和大小
    • 行尾风格
    • 文件末尾空行
  • 优先级说明:

    • 格式化工具(Prettier)> EditorConfig > 编辑器默认设置
    • 当 Prettier 运行时,它会覆盖 EditorConfig 的设置

项目根目录创建 .editorconfig 文件,添加配置如下:

# http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

赞(0)
未经允许不得转载:171主机测评 » vite+vue3+ts前端搭建与配置(5) -代码检查
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址