前言
本文介绍 vue3-element-admin 如何通过ESLint 检测 JS/TS 代码、Prettier 格式化代码、Stylelint 检测 CSS/SCSS 代码和配置 EditorConfig 来全方位约束和统一前端代码规范。
ESLint 代码检测
ESLint 可组装的JavaScript和JSX检查工具,目标是保证代码的一致性和避免错误。
ESLint 安装
安装 ESLint 插件
VSCode 插件市场搜索 ESLint 插件并安装
安装 ESLint 依赖
npm i -D eslint
ESLint 配置
ESLint 配置(.eslintrc.cjs)
执行命令完成 ESLint 配置初始化
npx eslint --init
根目录自动生成的 .eslintrc.cjs 配置内容如下:
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
"eslint:recommended",
"plugin:vue/vue3-essential",
"plugin:@typescript-eslint/recommended",
],
overrides: [],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
plugins: ["vue", "@typescript-eslint"],
rules: {},
};
ESLint 解析器配置
在默认配置基础上需要修改解析器为 vue-eslint-parser ,不然在检测执行中出现 error Parsing error: '>' expected 的解析错误,修改 .eslintrc.cjs 如下:
ESLint 忽略配置(.eslintignore)
根目录新建 .eslintignore 文件,添加忽略文件, ESLint 校验会忽略这些文件,配置如下:
dist
node_modules
public
.husky
.vscode
.idea
*.sh
*.md
src/assets
.eslintrc.cjs
.prettierrc.cjs
.stylelintrc.cjs
ESLint 检测指令
package.json 添加 eslint 检测指令:
"scripts": {
"lint:eslint": "eslint \"src/**/*.{vue,ts,js}\" --fix"
}
ESLint 检测
ESLint 检测 & 验证
执行命令进行ESLint检测:
npm run lint:eslint
ESLint 保存自动检测
打开 File → Preferences → Settings 搜索 Editor: Code Actions On Save 选择 Workspace标签设置工作区,点击 Edit in settings.json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true // 开启eslint自动检测
}
}
Prettier 代码格式化
Prettier 一个“有态度”的代码格式化工具。
Prettier 安装
安装 Prettier 插件
VSCode 插件市场搜索 Prettier - Code formatter 插件安装
安装 Prettier 依赖
npm install -D prettier
Prettier 配置
Prettier 配置 (.prettierrc.cjs)
根目录创建.prettierrc.cjs 文件,复制 官方默认配置 (详细配置:Prettier 中文网 - Options)
module.exports = {
// (x)=>{},单个参数箭头函数是否显示小括号。(always:始终显示;avoid:省略括号。默认:always)
arrowParens: "always",
// 开始标签的右尖括号是否跟随在最后一行属性末尾,默认false
bracketSameLine: false,
// 对象字面量的括号之间打印空格 (true - Example: { foo: bar } ; false - Example: {foo:bar})
bracketSpacing: true,
// 是否格式化一些文件中被嵌入的代码片段的风格(auto|off;默认auto)
embeddedLanguageFormatting: "auto",
// 指定 HTML 文件的空格敏感度 (css|strict|ignore;默认css)
htmlWhitespaceSensitivity: "css",
// 当文件已经被 Prettier 格式化之后,是否会在文件顶部插入一个特殊的 @format 标记,默认false
insertPragma: false,
// 在 JSX 中使用单引号替代双引号,默认false
jsxSingleQuote: false,
// 每行最多字符数量,超出换行(默认80)
printWidth: 120,
// 超出打印宽度 (always | never | preserve )
proseWrap: "preserve",
// 对象属性是否使用引号(as-needed | consistent | preserve;默认as-needed:对象的属性需要加引号才添加;)
quoteProps: "as-needed",
// 是否只格式化在文件顶部包含特定注释(@prettier| @format)的文件,默认false
requirePragma: false,
// 结尾添加分号
semi: true,
// 使用单引号 (true:单引号;false:双引号)
singleQuote: false,
// 缩进空格数,默认2个空格
tabWidth: 2,
// 元素末尾是否加逗号,默认es5: ES5中的 objects, arrays 等会添加逗号,TypeScript 中的 type 后不加逗号
trailingComma: "es5",
// 指定缩进方式,空格或tab,默认false,即使用空格
useTabs: false,
// vue 文件中是否缩进