代码规范
- Eslint + Prettier
安装
bash
pnpm i -D eslint @antfu/eslint-config
pnpm i prettier eslint-config-prettier eslint-plugin-prettier -D
pnpm i vite-plugin-eslint2 -D配置
在根目录下创建eslint.config.mjs 文件
js
import antfu from "@antfu/eslint-config";
const apps = "src";
const histoirePath = `${apps}`;
export default await antfu(
{
typescript: true,
vue: true,
ignores: [
"tsconfig.app.json",
"tsconfig.node.json",
"tsconfig.json",
"**/*.json",
".prettierrc.cjs",
"eslint.config.mjs",
"**/*.md",
"pnpm-workspace.yaml",
"uno.config.js",
],
rules: {
// 允许 } catch 在同一行
"style/brace-style": ["error", "1tbs", { allowSingleLine: true }],
},
},
// Histoire Overrides
{
files: [`${histoirePath}/**/*.{js,ts,vue}`],
rules: {
"import/default": "off",
// 允许console.log
"no-console": ["error", { allow: ["warn", "error", "log"] }],
// 单标签闭合关闭 类似 <img />
"vue/html-self-closing": "off",
// 多行属性换行 关闭 允许属性不换行
// 比如<button @click=xxx></button> 这样不用把@click换乘第二行
"vue/singleline-html-element-content-newline": "off",
"vue/multiline-html-element-content-newline": "off",
},
},
);在根目录下创建 .prettierrc 文件
- 创建
.prettierrc文件
json
{
"singleQuote": true,
"semi": false,
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"trailingComma": "all",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "avoid",
"endOfLine": "lf",
"jsxSingleQuote": false,
"quoteProps": "as-needed",
"singleAttributePerLine": true
}- 里面的格式对照
| 配置项 | 当前值 | 含义 |
|---|---|---|
| singleQuote | true | 字符串使用单引号 ' 而不是双引号 "(JSX 属性除外,由 jsxSingleQuote 控制) |
| semi | true | 语句末尾加分号 ; |
| printWidth | 120 | 每行最大宽度 120 字符,超过会自动换行(默认值是 80) |
| tabWidth | 2 | 每级缩进用 2 个空格 |
| useTabs | false | 缩进用空格,不用 Tab 字符 |
| trailingComma | "es5" | 在 ES5 合法的位置加尾随逗号(对象、数组会加;函数参数不加)。可选 "none" / "es5" / "all" |
| bracketSpacing | true | 对象花括号内加空格:{ foo: bar } 而非 {foo: bar} |
| bracketSameLine | false | JSX/HTML 元素的闭合 > 不放在最后一个属性的同一行,而是单独换行 |
| arrowParens | "always" | 箭头函数参数总是加括号:(x) => x,即使只有一个参数 |
| endOfLine | "lf" | 换行符统一用 LF(Unix 风格),避免 Windows CRLF 混用导致 git diff 噪音 |
| jsxSingleQuote | false | JSX 属性值用双引号:<div className="foo">,与 HTML 习惯一致 |
| quoteProps | "as-needed" | 对象属性名仅在必要时加引号(如包含特殊字符的 "foo-bar"),普通属性不加 |
根目录创建.prettierignore文件
- 他表示不需要代码美化文件的目录
bash
# 构建产物
dist
build
coverage
# 依赖目录
node_modules
# 锁文件
pnpm-lock.yaml
package-lock.json
yarn.lock
# 静态资源与二进制文件
*.svg
*.png
*.jpg
*.jpeg
*.gif
*.webp
*.ico
# 环境与日志文件
*.log
.env
.env.*
# 缓存目录
.cache
.vitevite.config.ts
js
import { fileURLToPath, URL } from "node:url";
import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite";
import vueDevTools from "vite-plugin-vue-devtools";
// 新增加 eslint
import eslint from "vite-plugin-eslint2";
// https://vite.dev/config/
export default defineConfig({
plugins: [vue(), vueDevTools(), eslint()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
});这样运行npm run dev即可,这样 eslint 就会自动检查代码规范了