Commit 26da7184 by MT-Joer

style: eslint注释

1 parent 228b6657
Showing 28 changed files with 1628 additions and 1156 deletions
...@@ -4,8 +4,8 @@ root = true ...@@ -4,8 +4,8 @@ root = true
charset=utf-8 charset=utf-8
end_of_line=lf end_of_line=lf
insert_final_newline=true insert_final_newline=true
indent_style=space indent_style=tab
indent_size=2 indent_size=4
max_line_length = 100 max_line_length = 100
trim_trailing_whitespace = true trim_trailing_whitespace = true
quote_type = single quote_type = single
......
...@@ -12,14 +12,14 @@ const logoDark = computed(() => preferences.logo.sourceDark); ...@@ -12,14 +12,14 @@ const logoDark = computed(() => preferences.logo.sourceDark);
</script> </script>
<template> <template>
<AuthPageLayout <AuthPageLayout
:app-name="appName" :app-name="appName"
:logo="logo" :logo="logo"
:logo-dark="logoDark" :logo-dark="logoDark"
:page-description="$t('authentication.pageDesc')" :page-description="$t('authentication.pageDesc')"
:page-title="$t('authentication.pageTitle')" :page-title="$t('authentication.pageTitle')"
> >
<!-- 自定义工具栏 --> <!-- 自定义工具栏 -->
<!-- <template #toolbar></template> --> <!-- <template #toolbar></template> -->
</AuthPageLayout> </AuthPageLayout>
</template> </template>
# 配置说明(注释汇总)
此文档对仓库内的 lint/format 配置做集中注释,解释各配置项为何这样设置,便于团队理解和维护。
---
## commitlint-config/index.mjs
- extends: ['@commitlint/config-conventional']
- 说明:使用广泛的 conventional commits 规则作为基础,保证 commit message 结构化(type(scope): subject)。
- 原因:便于生成变更日志、自动化发布与回滚策略,并提升协作一致性。
- plugins: ['commitlint-plugin-function-rules']
- 说明:启用自定义函数规则插件,用来做动态校验(例如 scope 白名单检查)。
- 原因:可以根据仓库状态(如 packages 列表)动态限制 scope,增强灵活性和正确性。
- prompt.alias / prompt.typesAppend / prompt.\*
- 说明:配置 `cz-git` 的交互式提示别名与类型扩充,包含中英文注释位于注释块中(被注释的部分为可选)。
- 原因:帮助开发者快速选择合适的 commit type,降低误提交概率,并保持提交信息规范。
- allowedScopes / scopeComplete
- 说明:`allowedScopes` 基于 monorepo 的 packages 名称和一些通用 scope(如 style, lint 等)。 `scopeComplete` 通过读取 git 工作树尝试预填充当前修改的 scope。
- 原因:提高提交时的便利性与准确性,避免随意填写非仓库相关 scope。
- rules:
- 'body-leading-blank': [2, 'always']
- 说明:要求 body 前有空行(error)。
- 原因:保持 header 与 body 的可读性,方便自动解析 changelog。
- 'footer-leading-blank': [1, 'always']
- 说明:footer 前建议空行(warning)。
- 原因:提高可读性并兼容一些解析工具的期望格式。
- 'function-rules/scope-enum': 自定义函数
- 说明:用函数校验 scope 是否在 allowedScopes 中。
- 原因:Allows dynamic validation using workspace packages, preventing incorrect scopes.
- 'header-max-length': [2, 'always', 108]
- 说明:header 最大长度 108 字符(error)。
- 原因:在保持信息完整的同时,避免过长的标题影响日志与显示。108 的选择折衷了英文与中文长度需求。
- 'subject-empty' / 'type-empty' 等
- 说明:确保 commit 包含 type 与 subject,不允许为空。
- 原因:维持提交信息的最小结构化约束,便于后续自动化处理。
- 'type-enum'
- 说明:限制 type 为特定集合(feat, fix, perf, ...)。
- 原因:统一团队约定,便于按类型筛选变更(如 release note 分组)。
---
## prettier-config/index.mjs
- endOfLine: 'auto'
- 说明:使用系统默认换行(LF/CRLF 自动处理)。
- 原因:跨平台项目(Windows / macOS / Linux)避免换行符引起的 diff 噪音。
- overrides: for '\*.json5' quoteProps: 'preserve', singleQuote: false
- 说明:对 JSON5 文件保留属性引号并使用双引号。
- 原因:JSON 格式通常使用双引号,保证与 JSON 语法和工具兼容。
- plugins: ['prettier-plugin-tailwindcss']
- 说明:集成 Tailwind CSS 类名排序插件。
- 原因:自动对 class 列表进行确定性排序,减少无意义的样式变动并提升可读性。
- printWidth: 120
- 说明:每行最大长度 120 字符。
- 原因:给现代宽屏编辑器更宽的视觉空间,兼顾可读性与代码行长度。
- proseWrap: 'never'
- 说明:不对 Markdown 中的文字内容进行自动折行。
- 原因:保留文本作者的意图与 diff 可读性,避免自动破坏文本结构。
- semi: true / singleQuote: true / trailingComma: 'all'
- 说明:启用分号、使用单引号、保持尾随逗号。
- 原因:符合团队编码风格,尾随逗号便利于多行 diff 时减少变更行数。
---
## stylelint-config/index.mjs
- extends: ['stylelint-config-standard', 'stylelint-config-recess-order']
- 说明:以标准规则与声明顺序插件为基础。
- 原因:保证 CSS/SCSS 基础校验并统一声明顺序提升可读性。
- ignoreFiles: '\*_/_.js, jsx, tsx, ts, json, md'
- 说明:跳过非样式文件的检查。
- 原因:这些文件不是纯样式文件,样式书写通常嵌入在模板或特定语法中,通过 overrides 处理。
- overrides: postcss-html / postcss-scss
- 说明:为 `.vue` / `.html` 使用 `postcss-html`,为 `.scss` 使用 `postcss-scss` 并扩展推荐的 scss/vue 配置。
- 原因:正确解析内联样式、模板中的 style 块与 SCSS 语法,避免误报。
- plugins: ['stylelint-order', '@stylistic/stylelint-plugin', 'stylelint-prettier', 'stylelint-scss']
- 说明:引入声明顺序、风格化、prettier 集成和 SCSS 支持插件。
- 原因:确保规则可组合、与 prettier 协同,以及对 SCSS 的增强校验。
- rules: (列举若干重点规则与原因)
- 'at-rule-no-unknown' / 'scss/at-rule-no-unknown' -> ignoreAtRules: [...]
- 说明:允许识别大量在构建或框架中常用的 at-rule(如 tailwind, include, mixin 等)。
- 原因:这些 at-rule 在 postcss 或 scss 中合法,忽略可以避免误报。
- 'order/order': 指定规则顺序
- 说明:定义了 CSS 中不同块(变量、自定义属性、at-rules、声明、规则等)的顺序。
- 原因:统一样式文件结构,提高可维护性和审阅效率。
- 'prettier/prettier': true
- 说明:启用 prettier 与 stylelint 的联动,由 prettier 负责格式化细节。
- 原因:避免规则冲突,让 prettier 负责格式类校验,stylelint 负责语义类校验。
- 'selector-class-pattern'
- 说明:限定 class 名的命名模式(支持 BEM 与常用前缀如 o/c/u/t 等)。
- 原因:强制一致的命名约定,便于大型项目协作与样式复用。
---
## eslint-config (internal/lint-configs/eslint-config)
总体说明:此包通过 `defineConfig` 异步组合多个子配置模块(如 vue, typescript, prettier 等),把复杂的 lint 规则拆分为可维护的子模块,最后汇总成 flat config。这样结构便于按需加载与复用。
- src/index.ts
- defineConfig([...])
- 说明:按固定顺序加载 `vue(), javascript(), ignores(), prettier(), typescript(), jsonc(), ...` 等配置。
- 原因:顺序有讲究,例如先解析语言特性再应用 prettier 强制,某些插件需先注册才能生效;此外把 ignores 放在靠前的位置能避免不必要的规则应用。
- src/custom-config.ts
- 说明:专门为 monorepo 各子包/目录定义的覆盖规则(files/ignores/rules),例如对 `packages/@core`、`apps`、`backend-mock`、`internal` 等有定制化规则。
- 原因:monorepo 中不同包的约束不同——比如生成文件、后端 mock、内部脚本允许更多自由度;通过 `files` 精确控制,可以减少误报并保持一致性。
- 关键点解释:
- restrictedImportIgnores: 列出在某些文件中放宽 import 限制的文件(如 build 配置文件)。
- 多处使用 `no-restricted-imports`:用于避免子包之间错误依赖(例如禁止 @core 引入 @vben),保证包边界清晰,防止循环或不正确的依赖结构。
- 在 `apps/backend-mock/**` 和 `docs/**` 中关闭若干规则:这些目录通常为示例/测试/脚本,降低规则可以提高开发效率。
- src/configs/\*
- 说明:configs 目录把各类规则按关注点拆分(command、comments、import、javascript、typescript、vue、prettier 等),每个模块负责自己的规则集合。
- 原因:模块化便于维护与扩展,减少单一文件臃肿并能按需导出/测试。
- 与 prettier 的整合
- 说明:prettier 模块被包含在 configs 中,保证格式化规则与 eslint 联动(prettier 通常要在 rules 或 plugin 中禁用与格式相关的规则)。
- 原因:避免格式化规则与代码质量规则冲突,让 prettier 处理样式问题,eslint 侧重语义错误与最佳实践。
- perfectionist / unicorn / node / jsdoc 等插件
- 说明:引入多个插件(如 perfectionist 用于排序/风格一致性,unicorn 提供更好的 JS/TS 建议,jsdoc 用于文档注释校验)。
- 原因:通过插件生态补足 core eslint 的能力,提升代码质量与一致性。
---
## 建议与注意事项
- 若要把注释直接加回到配置源文件(作为 inline comment),我可以帮助逐文件修改并在每处配置上添加简短中文注释;但这会修改仓库文件。当前我已把集中注释保存在 `internal/lint-configs/ANNOTATIONS.md`,便于审阅。
- 推荐把 `ANNOTATIONS.md` 与 CI 或贡献指南链接,方便新成员快速了解配置意图。
- 若需要,我可以继续:
- 逐文件插入 inline 注释并提交 PR。
- 为每个子配置生成更细粒度的解释(例如把 eslint rule 的解释展开到单条规则)。
---
文档生成于仓库 `internal/lint-configs`,如需将注释写入原始配置文件或生成 PR,请告诉我下一步。
/*
commitlint-config/index.mjs
目的:配置 commitlint(cz-git)以强制仓库的 commit message 规范。
关键点:
- 使用 conventional commits 作为基础以支持自动化 changelog/release
- 通过插件和脚本动态生成 scope 白名单(基于 monorepo packages)
- 为交互式提交提示提供别名/默认值以降低误提交成本
注意:该文件通过读取 git 状态来尝试预填充 scope(提高体验)。
*/
import { execSync } from 'node:child_process'; import { execSync } from 'node:child_process';
import { getPackagesSync } from '@vben/node-utils'; import { getPackagesSync } from '@vben/node-utils';
...@@ -5,149 +17,152 @@ import { getPackagesSync } from '@vben/node-utils'; ...@@ -5,149 +17,152 @@ import { getPackagesSync } from '@vben/node-utils';
const { packages } = getPackagesSync(); const { packages } = getPackagesSync();
const allowedScopes = [ const allowedScopes = [
...packages.map((pkg) => pkg.packageJson.name), ...packages.map((pkg) => pkg.packageJson.name),
'project', 'project',
'style', 'style',
'lint', 'lint',
'ci', 'ci',
'dev', 'dev',
'deploy', 'deploy',
'other', 'other',
]; ];
// precomputed scope // precomputed scope
const scopeComplete = execSync('git status --porcelain || true') const scopeComplete = execSync('git status --porcelain || true')
.toString() .toString()
.trim() .trim()
.split('\n') .split('\n')
.find((r) => ~r.indexOf('M src')) .find((r) => ~r.indexOf('M src'))
?.replaceAll(/(\/)/g, '%%') ?.replaceAll(/(\/)/g, '%%')
?.match(/src%%((\w|-)*)/)?.[1] ?.match(/src%%((\w|-)*)/)?.[1]
?.replace(/s$/, ''); ?.replace(/s$/, '');
/** /**
* @type {import('cz-git').UserConfig} * @type {import('cz-git').UserConfig}
*/ */
const userConfig = { const userConfig = {
extends: ['@commitlint/config-conventional'], extends: ['@commitlint/config-conventional'],
plugins: ['commitlint-plugin-function-rules'], plugins: ['commitlint-plugin-function-rules'],
prompt: { prompt: {
/** @use `pnpm commit :f` */ /** @use `pnpm commit :f` */
alias: { alias: {
b: 'build: bump dependencies', b: 'build: bump dependencies',
c: 'chore: update config', c: 'chore: update config',
f: 'docs: fix typos', f: 'docs: fix typos',
r: 'docs: update README', r: 'docs: update README',
s: 'style: update code format', s: 'style: update code format',
}, },
allowCustomIssuePrefixs: false, allowCustomIssuePrefixs: false,
// scopes: [...scopes, 'mock'], // scopes: [...scopes, 'mock'],
allowEmptyIssuePrefixs: false, allowEmptyIssuePrefixs: false,
customScopesAlign: scopeComplete ? 'bottom' : 'top', customScopesAlign: scopeComplete ? 'bottom' : 'top',
defaultScope: scopeComplete, defaultScope: scopeComplete,
// English // English
typesAppend: [ typesAppend: [
{ name: 'workflow: workflow improvements', value: 'workflow' }, { name: 'workflow: workflow improvements', value: 'workflow' },
{ name: 'types: type definition file changes', value: 'types' }, { name: 'types: type definition file changes', value: 'types' },
], ],
// 中英文对照版 // 中英文对照版
// messages: { // messages: {
// type: '选择你要提交的类型 :', // type: '选择你要提交的类型 :',
// scope: '选择一个提交范围 (可选):', // scope: '选择一个提交范围 (可选):',
// customScope: '请输入自定义的提交范围 :', // customScope: '请输入自定义的提交范围 :',
// subject: '填写简短精炼的变更描述 :\n', // subject: '填写简短精炼的变更描述 :\n',
// body: '填写更加详细的变更描述 (可选)。使用 "|" 换行 :\n', // body: '填写更加详细的变更描述 (可选)。使用 "|" 换行 :\n',
// breaking: '列举非兼容性重大的变更 (可选)。使用 "|" 换行 :\n', // breaking: '列举非兼容性重大的变更 (可选)。使用 "|" 换行 :\n',
// footerPrefixsSelect: '选择关联issue前缀 (可选):', // footerPrefixsSelect: '选择关联issue前缀 (可选):',
// customFooterPrefixs: '输入自定义issue前缀 :', // customFooterPrefixs: '输入自定义issue前缀 :',
// footer: '列举关联issue (可选) 例如: #31, #I3244 :\n', // footer: '列举关联issue (可选) 例如: #31, #I3244 :\n',
// confirmCommit: '是否提交或修改commit ?', // confirmCommit: '是否提交或修改commit ?',
// }, // },
// types: [ // types: [
// { value: 'feat', name: 'feat: 新增功能' }, // { value: 'feat', name: 'feat: 新增功能' },
// { value: 'fix', name: 'fix: 修复缺陷' }, // { value: 'fix', name: 'fix: 修复缺陷' },
// { value: 'docs', name: 'docs: 文档变更' }, // { value: 'docs', name: 'docs: 文档变更' },
// { value: 'style', name: 'style: 代码格式' }, // { value: 'style', name: 'style: 代码格式' },
// { value: 'refactor', name: 'refactor: 代码重构' }, // { value: 'refactor', name: 'refactor: 代码重构' },
// { value: 'perf', name: 'perf: 性能优化' }, // { value: 'perf', name: 'perf: 性能优化' },
// { value: 'test', name: 'test: 添加疏漏测试或已有测试改动' }, // { value: 'test', name: 'test: 添加疏漏测试或已有测试改动' },
// { value: 'build', name: 'build: 构建流程、外部依赖变更 (如升级 npm 包、修改打包配置等)' }, // { value: 'build', name: 'build: 构建流程、外部依赖变更 (如升级 npm 包、修改打包配置等)' },
// { value: 'ci', name: 'ci: 修改 CI 配置、脚本' }, // { value: 'ci', name: 'ci: 修改 CI 配置、脚本' },
// { value: 'revert', name: 'revert: 回滚 commit' }, // { value: 'revert', name: 'revert: 回滚 commit' },
// { value: 'chore', name: 'chore: 对构建过程或辅助工具和库的更改 (不影响源文件、测试用例)' }, // { value: 'chore', name: 'chore: 对构建过程或辅助工具和库的更改 (不影响源文件、测试用例)' },
// { value: 'wip', name: 'wip: 正在开发中' }, // { value: 'wip', name: 'wip: 正在开发中' },
// { value: 'workflow', name: 'workflow: 工作流程改进' }, // { value: 'workflow', name: 'workflow: 工作流程改进' },
// { value: 'types', name: 'types: 类型定义文件修改' }, // { value: 'types', name: 'types: 类型定义文件修改' },
// ], // ],
// emptyScopesAlias: 'empty: 不填写', // emptyScopesAlias: 'empty: 不填写',
// customScopesAlias: 'custom: 自定义', // customScopesAlias: 'custom: 自定义',
}, },
rules: { rules: {
/** /**
* type[scope]: [function] description * type[scope]: [function] description
* *
* ^^^^^^^^^^^^^^ empty line. * ^^^^^^^^^^^^^^ empty line.
* - Something here * - Something here
*/ */
'body-leading-blank': [2, 'always'], 'body-leading-blank': [2, 'always'],
/** /**
* type[scope]: [function] description * type[scope]: [function] description
* *
* - something here * - something here
* *
* ^^^^^^^^^^^^^^ * ^^^^^^^^^^^^^^
*/ */
'footer-leading-blank': [1, 'always'], 'footer-leading-blank': [1, 'always'],
/** /**
* type[scope]: [function] description * type[scope]: [function] description
* ^^^^^ * ^^^^^
*/ */
'function-rules/scope-enum': [ 'function-rules/scope-enum': [
2, // level: error 2, // level: error
'always', 'always',
(parsed) => { (parsed) => {
if (!parsed.scope || allowedScopes.includes(parsed.scope)) { if (!parsed.scope || allowedScopes.includes(parsed.scope)) {
return [true]; return [true];
} }
return [false, `scope must be one of ${allowedScopes.join(', ')}`]; return [
}, false,
], `scope must be one of ${allowedScopes.join(', ')}`,
/** ];
* type[scope]: [function] description [No more than 108 characters] },
* ^^^^^ ],
*/ /**
'header-max-length': [2, 'always', 108], * type[scope]: [function] description [No more than 108 characters]
* ^^^^^
*/
'header-max-length': [2, 'always', 108],
'scope-enum': [0], 'scope-enum': [0],
'subject-case': [0], 'subject-case': [0],
'subject-empty': [2, 'never'], 'subject-empty': [2, 'never'],
'type-empty': [2, 'never'], 'type-empty': [2, 'never'],
/** /**
* type[scope]: [function] description * type[scope]: [function] description
* ^^^^ * ^^^^
*/ */
'type-enum': [ 'type-enum': [
2, 2,
'always', 'always',
[ [
'feat', 'feat',
'fix', 'fix',
'perf', 'perf',
'style', 'style',
'docs', 'docs',
'test', 'test',
'refactor', 'refactor',
'build', 'build',
'ci', 'ci',
'chore', 'chore',
'revert', 'revert',
'types', 'types',
'release', 'release',
], ],
], ],
}, },
}; };
export default userConfig; export default userConfig;
# ESLint 规则详解(仓库级)
此文档为 `internal/lint-configs/eslint-config` 的补充,逐条说明常见规则、插件及其为何在 monorepo 中被启用/禁用。
目录
- no-restricted-imports
- perfectionist(排序相关)
- unicorn(现代化建议)
- @typescript-eslint(类型检查相关)
- prettier 与 eslint 的协作
- jsdoc
- node / n 插件
- regexp / turbo / test 模块用途
- overrides 与 files/ignores 的设计理念
---
no-restricted-imports
- 作用:禁止特定模块或路径的导入,可指定 message 给出替代方案。
- 常见用法:在 monorepo 中阻止子包直接依赖另一个包的内部实现(例如禁止 `@core` 导入 `@vben/*`)。
- 为什么:保持包边界、避免紧耦合、促进清晰的公共 API 设计,降低后续重构成本。
- 注意点:在构建配置文件(vite/tailwind/postcss)中允许特定导入(通过 restrictedImportIgnores),以便工具正常运行。
perfectionist(排序相关)
- 作用:对对象属性、导出、接口成员等做一致性排序(alphabetical 或自定义策略)。
- 为什么:统一排序减少无意义的 diff,提升代码可读性与审查效率。
- 何时禁用:对于代码自动生成产物或特定结构化/语义重要的对象,排序可能破坏含义,此时会在 custom-config 中关闭相关规则。
unicorn
- 作用:提供一组现代 JS/TS 最佳实践(如使用 `Array.isArray`、避免隐式类型转换、用更语义化的方法替代低级 API 等)。
- 为什么:提升一致性与安全性,避免常见陷阱。
- 何时关闭:脚本、mock、demo 或 legacy 代码中可有选择关闭,以减少误报并提升开发灵活性。
@typescript-eslint
- 常见规则:`no-explicit-any`、`explicit-module-boundary-types`、`consistent-type-assertions` 等。
- 目的:强化类型层面的检查,捕获潜在类型错误,提升代码健壮性。
- 平衡点:严格规则能提高质量,但会增加迁移/重构成本。对生成代码或快速迭代目录可适当放宽。
prettier 与 eslint 的协作
- 原则:让 Prettier 负责格式(空格、单双引号、换行、尾逗号等),让 ESLint 负责语义/最佳实践。
- 实践:在 ESLint 配置中禁用与格式相关的规则(或使用 `eslint-config-prettier`),并通过 `prettier` 插件在 stylelint 中启用 `prettier/prettier`。
- 好处:避免工具间冲突,统一格式化输出,减少“格式导致的 lint 报错”。
jsdoc
- 用途:对公共 API 的注释进行校验,保证参数、返回值说明完整。
- 场景:对于 packages 下的库/组件包(对外 API)建议开启;对脚本或 demo 目录可关闭以减少噪音。
node / n 插件
- 作用:检查 Node 环境相关的最佳实践(如依赖声明、全局对象偏好等)。
- 场景:在 backend-mock、脚本或工具目录中放宽某些规则(例如 `n/no-extraneous-import`),以支持开发便利性。
regexp / turbo / test 模块
- 说明:这些模块把针对性的规则归类(正则安全、turbo monorepo 配置、测试文件的特殊规则),便于管理和定位问题。
- 目的:减少全局规则的复杂度,通过模块化针对不同场景提供不同强度的校验。
overrides 与 files/ignores 的设计理念
- 原则:使用 `files`/`ignores` 精确控制规则的作用范围——越精确越少误报。
- 实践:
- 对构建/配置文件放宽某些限制(允许使用 Node 全局等)。
- 对 `packages/@core/**` 强制边界规则,避免跨包直接依赖。
- 对 demo/docs/mock 放宽大量规则以便快速迭代。
---
下一步建议
- 若希望把每个子模块的每一条 rule 都写成 inline 注释(便于在代码编辑器中直接查看),我可以按照优先级逐步将注释写入 `internal/lint-configs/eslint-config/src/configs` 下的文件:
- 阶段 A(必做):对 `prettier.ts`、`import.ts`、`typescript.ts`、`vue.ts` 添加逐条注释(解释为何开启/关闭某条规则)。
- 阶段 B(可选):对其余模块(如 `unicorn.ts`、`perfectionist.ts`、`node.ts`)执行同样操作。
请回复要执行的方案(例如:`inline 全部`、`inline A 阶段`、`仅生成 DOCS.md`)。
/*
eslint-config/src/configs/command.ts
说明:ESLint 命令注释支持(eslint-plugin-command),允许通过注释下达 lint 命令。
要点:
- 该插件较简洁,直接返回创建的配置对象
*/
import createCommand from 'eslint-plugin-command/config'; import createCommand from 'eslint-plugin-command/config';
export async function command() { export async function command() {
return [ return [
{ {
...createCommand(), ...createCommand(),
}, },
]; ];
} }
/*
eslint-config/src/configs/comments.ts
说明:ESLint 注释指令规则(eslint-plugin-eslint-comments)用于规范禁用注释。
要点:
- 禁止聚合多个规则到一个 enable 注释(需要分别 enable)
- 禁止重复禁用或未使用的 enable 注释
- 防止过度使用 eslint-disable-next-line
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function comments(): Promise<Linter.Config[]> { export async function comments(): Promise<Linter.Config[]> {
const [pluginComments] = await Promise.all([ const [pluginComments] = await Promise.all([
// @ts-expect-error - no types // @ts-expect-error - no types
interopDefault(import('eslint-plugin-eslint-comments')), interopDefault(import('eslint-plugin-eslint-comments')),
] as const); ] as const);
return [ return [
{ {
plugins: { plugins: {
'eslint-comments': pluginComments, 'eslint-comments': pluginComments,
}, },
rules: { rules: {
'eslint-comments/no-aggregating-enable': 'error', 'eslint-comments/no-aggregating-enable': 'error',
'eslint-comments/no-duplicate-disable': 'error', 'eslint-comments/no-duplicate-disable': 'error',
'eslint-comments/no-unlimited-disable': 'error', 'eslint-comments/no-unlimited-disable': 'error',
'eslint-comments/no-unused-enable': 'error', 'eslint-comments/no-unused-enable': 'error',
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/disableds.ts
说明:针对特定文件类型禁用某些不适用的规则以避免误报。
要点:
- 测试文件中禁用 @ts-comment 与 console 限制
- .d.ts 类型定义文件禁用三斜线引用检查(可能需要三斜线引用 lib)
- 纯 JS 文件禁用 TS 特定规则
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
export async function disableds(): Promise<Linter.Config[]> { export async function disableds(): Promise<Linter.Config[]> {
return [ return [
{ {
files: ['**/__tests__/**/*.?([cm])[jt]s?(x)'], files: ['**/__tests__/**/*.?([cm])[jt]s?(x)'],
name: 'disables/test', name: 'disables/test',
rules: { rules: {
'@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/ban-ts-comment': 'off',
'no-console': 'off', 'no-console': 'off',
}, },
}, },
{ {
files: ['**/*.d.ts'], files: ['**/*.d.ts'],
name: 'disables/dts', name: 'disables/dts',
rules: { rules: {
'@typescript-eslint/triple-slash-reference': 'off', '@typescript-eslint/triple-slash-reference': 'off',
}, },
}, },
{ {
files: ['**/*.js', '**/*.mjs', '**/*.cjs'], files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
name: 'disables/js', name: 'disables/js',
rules: { rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off',
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/ignores.ts
说明:配置全仓库的忽略文件模式(node_modules, dist, build outputs 等)。
要点:
- 忽略构建产物和依赖目录以加速 lint 速度
- 忽略自动生成的文件(auto-imports.d.ts, components.d.ts 等)
- 忽略配置缓存和临时目录
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
export async function ignores(): Promise<Linter.Config[]> { export async function ignores(): Promise<Linter.Config[]> {
return [ return [
{ {
ignores: [ ignores: [
'**/node_modules', '**/node_modules',
'**/dist', '**/dist',
'**/dist-*', '**/dist-*',
'**/*-dist', '**/*-dist',
'**/.husky', '**/.husky',
'**/.nitro', '**/.nitro',
'**/.output', '**/.output',
'**/Dockerfile', '**/Dockerfile',
'**/package-lock.json', '**/package-lock.json',
'**/yarn.lock', '**/yarn.lock',
'**/pnpm-lock.yaml', '**/pnpm-lock.yaml',
'**/bun.lockb', '**/bun.lockb',
'**/output', '**/output',
'**/coverage', '**/coverage',
'**/temp', '**/temp',
'**/.temp', '**/.temp',
'**/tmp', '**/tmp',
'**/.tmp', '**/.tmp',
'**/.history', '**/.history',
'**/.turbo', '**/.turbo',
'**/.nuxt', '**/.nuxt',
'**/.next', '**/.next',
'**/.vercel', '**/.vercel',
'**/.changeset', '**/.changeset',
'**/.idea', '**/.idea',
'**/.cache', '**/.cache',
'**/.output', '**/.output',
'**/.vite-inspect', '**/.vite-inspect',
'**/CHANGELOG*.md', '**/CHANGELOG*.md',
'**/*.min.*', '**/*.min.*',
'**/LICENSE*', '**/LICENSE*',
'**/__snapshots__', '**/__snapshots__',
'**/*.snap', '**/*.snap',
'**/fixtures/**', '**/fixtures/**',
'**/.vitepress/cache/**', '**/.vitepress/cache/**',
'**/auto-import?(s).d.ts', '**/auto-import?(s).d.ts',
'**/components.d.ts', '**/components.d.ts',
'**/vite.config.mts.*', '**/vite.config.mts.*',
'**/*.sh', '**/*.sh',
'**/*.ttf', '**/*.ttf',
'**/*.woff', '**/*.woff',
], ],
}, },
]; ];
} }
/*
eslint-config/src/configs/import.ts
说明:import 插件用于规整模块导入风格与检查可能的错误导入。
要点:
- 强制 import 顺序/风格以提升可读性
- 在 monorepo 场景下对 `import/no-unresolved` 适度关闭以兼容工作区解析
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import * as pluginImport from 'eslint-plugin-import-x'; import * as pluginImport from 'eslint-plugin-import-x';
export async function importPluginConfig(): Promise<Linter.Config[]> { export async function importPluginConfig(): Promise<Linter.Config[]> {
return [ return [
{ {
plugins: { plugins: {
// @ts-expect-error - This is a dynamic import // @ts-expect-error - This is a dynamic import
import: pluginImport, import: pluginImport,
}, },
rules: { rules: {
'import/consistent-type-specifier-style': ['error', 'prefer-top-level'], // 优先在顶层位置声明类型导出,减少嵌套导致的类型混淆
'import/first': 'error', 'import/consistent-type-specifier-style': [
'import/newline-after-import': 'error', 'error',
'import/no-duplicates': 'error', 'prefer-top-level',
'import/no-mutable-exports': 'error', ],
'import/no-named-default': 'error', // 导入应集中在文件顶部
'import/no-self-import': 'error', 'import/first': 'error',
'import/no-unresolved': 'off', // 导入后需换行以增强可读性
'import/no-webpack-loader-syntax': 'error', 'import/newline-after-import': 'error',
}, 'import/no-duplicates': 'error',
}, 'import/no-mutable-exports': 'error',
]; 'import/no-named-default': 'error',
'import/no-self-import': 'error',
// monorepo/webpack/resolver 情况复杂,关闭此规则以避免误报(由打包器处理解析)
'import/no-unresolved': 'off',
'import/no-webpack-loader-syntax': 'error',
},
},
];
} }
...@@ -15,3 +15,10 @@ export * from './turbo'; ...@@ -15,3 +15,10 @@ export * from './turbo';
export * from './typescript'; export * from './typescript';
export * from './unicorn'; export * from './unicorn';
export * from './vue'; export * from './vue';
/*
eslint-config/src/configs/index.ts
说明:将各子配置模块集中导出,便于 `defineConfig` 按需加载。
注:每个子模块负责单一职责(例如 import 规则、typescript 规则、vue 规则等),易于维护与测试。
*/
/*
eslint-config/src/configs/jsdoc.ts
说明:JSDoc 规则(eslint-plugin-jsdoc)用于检查文档注释的完整性与准确性。
要点:
- 对库/公共 API 包推荐启用此规则确保文档完整
- 在此处启用为 warn 级别,允许对脚本/内部代码在 custom-config 中禁用
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function jsdoc(): Promise<Linter.Config[]> { export async function jsdoc(): Promise<Linter.Config[]> {
const [pluginJsdoc] = await Promise.all([ const [pluginJsdoc] = await Promise.all([
interopDefault(import('eslint-plugin-jsdoc')), interopDefault(import('eslint-plugin-jsdoc')),
] as const); ] as const);
return [ return [
{ {
plugins: { plugins: {
jsdoc: pluginJsdoc, jsdoc: pluginJsdoc,
}, },
rules: { rules: {
'jsdoc/check-access': 'warn', 'jsdoc/check-access': 'warn',
'jsdoc/check-param-names': 'warn', 'jsdoc/check-param-names': 'warn',
'jsdoc/check-property-names': 'warn', 'jsdoc/check-property-names': 'warn',
'jsdoc/check-types': 'warn', 'jsdoc/check-types': 'warn',
'jsdoc/empty-tags': 'warn', 'jsdoc/empty-tags': 'warn',
'jsdoc/implements-on-classes': 'warn', 'jsdoc/implements-on-classes': 'warn',
'jsdoc/no-defaults': 'warn', 'jsdoc/no-defaults': 'warn',
'jsdoc/no-multi-asterisks': 'warn', 'jsdoc/no-multi-asterisks': 'warn',
'jsdoc/require-param-name': 'warn', 'jsdoc/require-param-name': 'warn',
'jsdoc/require-property': 'warn', 'jsdoc/require-property': 'warn',
'jsdoc/require-property-description': 'warn', 'jsdoc/require-property-description': 'warn',
'jsdoc/require-property-name': 'warn', 'jsdoc/require-property-name': 'warn',
'jsdoc/require-returns-check': 'warn', 'jsdoc/require-returns-check': 'warn',
'jsdoc/require-returns-description': 'warn', 'jsdoc/require-returns-description': 'warn',
'jsdoc/require-yields-check': 'warn', 'jsdoc/require-yields-check': 'warn',
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/node.ts
说明:Node.js 环境规则(eslint-plugin-n),用于检查后端代码和脚本。
要点:
- 限制全局 buffer/process 使用以鼓励更显式的导入
- 在脚本和内部目录中放宽 process 限制
- 白名单化某些允许的外部 import(如 vitest, vite 等开发工具)
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function node(): Promise<Linter.Config[]> { export async function node(): Promise<Linter.Config[]> {
const pluginNode = await interopDefault(import('eslint-plugin-n')); const pluginNode = await interopDefault(import('eslint-plugin-n'));
return [ return [
{ {
plugins: { plugins: {
n: pluginNode, n: pluginNode,
}, },
rules: { rules: {
'n/handle-callback-err': ['error', '^(err|error)$'], 'n/handle-callback-err': ['error', '^(err|error)$'],
'n/no-deprecated-api': 'error', 'n/no-deprecated-api': 'error',
'n/no-exports-assign': 'error', 'n/no-exports-assign': 'error',
'n/no-extraneous-import': [ 'n/no-extraneous-import': [
'error', 'error',
{ {
allowModules: [ allowModules: [
'unbuild', 'unbuild',
'@vben/vite-config', '@vben/vite-config',
'vitest', 'vitest',
'vite', 'vite',
'@vue/test-utils', '@vue/test-utils',
'@vben/tailwind-config', '@vben/tailwind-config',
'@playwright/test', '@playwright/test',
], ],
}, },
], ],
'n/no-new-require': 'error', 'n/no-new-require': 'error',
'n/no-path-concat': 'error', 'n/no-path-concat': 'error',
// 'n/no-unpublished-import': 'off', // 'n/no-unpublished-import': 'off',
'n/no-unsupported-features/es-syntax': [ 'n/no-unsupported-features/es-syntax': [
'error', 'error',
{ {
ignores: [], ignores: [],
version: '>=20.12.0', version: '>=20.12.0',
}, },
], ],
'n/prefer-global/buffer': ['error', 'never'], 'n/prefer-global/buffer': ['error', 'never'],
// 'n/no-missing-import': 'off', // 'n/no-missing-import': 'off',
'n/prefer-global/process': ['error', 'never'], 'n/prefer-global/process': ['error', 'never'],
'n/process-exit-as-throw': 'error', 'n/process-exit-as-throw': 'error',
}, },
}, },
{ {
files: [ files: [
'scripts/**/*.?([cm])[jt]s?(x)', 'scripts/**/*.?([cm])[jt]s?(x)',
'internal/**/*.?([cm])[jt]s?(x)', 'internal/**/*.?([cm])[jt]s?(x)',
], ],
rules: { rules: {
'n/prefer-global/process': 'off', 'n/prefer-global/process': 'off',
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/perfectionist.ts
说明:Perfectionist 插件用于强制排序(imports、exports、对象等)以减少无意义变动。
要点:
- 对 import 进行多维度排序(type/external/vue/vben/internal 等分组)
- 对 export 和 named-export 进行排序
- 对 objects 默认关闭以保留语义顺序,可按需在 custom-config 中调整
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function perfectionist(): Promise<Linter.Config[]> { export async function perfectionist(): Promise<Linter.Config[]> {
const perfectionistPlugin = await interopDefault( const perfectionistPlugin = await interopDefault(
import('eslint-plugin-perfectionist'), import('eslint-plugin-perfectionist'),
); );
return [ return [
perfectionistPlugin.configs['recommended-natural'], perfectionistPlugin.configs['recommended-natural'],
{ {
rules: { rules: {
'perfectionist/sort-exports': [ 'perfectionist/sort-exports': [
'error', 'error',
{ {
order: 'asc', order: 'asc',
type: 'natural', type: 'natural',
}, },
], ],
'perfectionist/sort-imports': [ 'perfectionist/sort-imports': [
'error', 'error',
{ {
customGroups: { customGroups: {
type: { type: {
'vben-core-type': ['^@vben-core/.+'], 'vben-core-type': ['^@vben-core/.+'],
'vben-type': ['^@vben/.+'], 'vben-type': ['^@vben/.+'],
'vue-type': ['^vue$', '^vue-.+', '^@vue/.+'], 'vue-type': ['^vue$', '^vue-.+', '^@vue/.+'],
}, },
value: { value: {
vben: ['^@vben/.+'], vben: ['^@vben/.+'],
'vben-core': ['^@vben-core/.+'], 'vben-core': ['^@vben-core/.+'],
vue: ['^vue$', '^vue-.+', '^@vue/.+'], vue: ['^vue$', '^vue-.+', '^@vue/.+'],
}, },
}, },
environment: 'node', environment: 'node',
groups: [ groups: [
['external-type', 'builtin-type', 'type'], ['external-type', 'builtin-type', 'type'],
'vue-type', 'vue-type',
'vben-type', 'vben-type',
'vben-core-type', 'vben-core-type',
['parent-type', 'sibling-type', 'index-type'], ['parent-type', 'sibling-type', 'index-type'],
['internal-type'], ['internal-type'],
'builtin', 'builtin',
'vue', 'vue',
'vben', 'vben',
'vben-core', 'vben-core',
'external', 'external',
'internal', 'internal',
['parent', 'sibling', 'index'], ['parent', 'sibling', 'index'],
'side-effect', 'side-effect',
'side-effect-style', 'side-effect-style',
'style', 'style',
'object', 'object',
'unknown', 'unknown',
], ],
internalPattern: ['^#/.+'], internalPattern: ['^#/.+'],
newlinesBetween: 'always', newlinesBetween: 'always',
order: 'asc', order: 'asc',
type: 'natural', type: 'natural',
}, },
], ],
'perfectionist/sort-modules': 'off', 'perfectionist/sort-modules': 'off',
'perfectionist/sort-named-exports': [ 'perfectionist/sort-named-exports': [
'error', 'error',
{ {
order: 'asc', order: 'asc',
type: 'natural', type: 'natural',
}, },
], ],
'perfectionist/sort-objects': [ 'perfectionist/sort-objects': [
'off', 'off',
{ {
customGroups: { customGroups: {
items: 'items', items: 'items',
list: 'list', list: 'list',
children: 'children', children: 'children',
}, },
groups: ['unknown', 'items', 'list', 'children'], groups: ['unknown', 'items', 'list', 'children'],
ignorePattern: ['children'], ignorePattern: ['children'],
order: 'asc', order: 'asc',
type: 'natural', type: 'natural',
}, },
], ],
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/prettier.ts
说明:将 Prettier 与 ESLint 联动(通过 `eslint-plugin-prettier`),让 Prettier 负责格式化相关规则。
要点:
- 将 `prettier/prettier` 设为 error,CI 上确保格式化一致性
- 在此处仅启用插件与规则,具体格式由仓库根/包级 prettier 配置控制
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function prettier(): Promise<Linter.Config[]> { export async function prettier(): Promise<Linter.Config[]> {
const [pluginPrettier] = await Promise.all([ const [pluginPrettier] = await Promise.all([
interopDefault(import('eslint-plugin-prettier')), interopDefault(import('eslint-plugin-prettier')),
] as const); ] as const);
return [ return [
{ {
plugins: { plugins: {
prettier: pluginPrettier, prettier: pluginPrettier,
}, },
rules: { rules: {
'prettier/prettier': 'error', // 由 Prettier 统一负责格式,报告为 error 以在 CI 中强制通过格式检查
}, 'prettier/prettier': 'error',
}, },
]; },
];
} }
/*
eslint-config/src/configs/regexp.ts
说明:正则表达式安全规则(eslint-plugin-regexp)以防止常见的正则错误。
要点:
- 使用插件推荐配置即可
- 避免性能问题、空字符、多字符重复等常见正则缺陷
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function regexp(): Promise<Linter.Config[]> { export async function regexp(): Promise<Linter.Config[]> {
const [pluginRegexp] = await Promise.all([ const [pluginRegexp] = await Promise.all([
interopDefault(import('eslint-plugin-regexp')), interopDefault(import('eslint-plugin-regexp')),
] as const); ] as const);
return [ return [
{ {
plugins: { plugins: {
regexp: pluginRegexp, regexp: pluginRegexp,
}, },
rules: { rules: {
...pluginRegexp.configs.recommended.rules, ...pluginRegexp.configs.recommended.rules,
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/test.ts
说明:测试文件专属规则(vitest 与 no-only-tests)以规范测试编写与运行。
要点:
- 限制匹配 __tests__、*.spec、*.test 等模式的文件
- 禁止 console.log 的限制被放宽以便调试
- 禁止测试中的 .only 以防止提交未完成的定向测试
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function test(): Promise<Linter.Config[]> { export async function test(): Promise<Linter.Config[]> {
const [pluginTest, pluginNoOnlyTests] = await Promise.all([ const [pluginTest, pluginNoOnlyTests] = await Promise.all([
interopDefault(import('eslint-plugin-vitest')), interopDefault(import('eslint-plugin-vitest')),
// @ts-expect-error - no types // @ts-expect-error - no types
interopDefault(import('eslint-plugin-no-only-tests')), interopDefault(import('eslint-plugin-no-only-tests')),
] as const); ] as const);
return [ return [
{ {
files: [ files: [
`**/__tests__/**/*.?([cm])[jt]s?(x)`, `**/__tests__/**/*.?([cm])[jt]s?(x)`,
`**/*.spec.?([cm])[jt]s?(x)`, `**/*.spec.?([cm])[jt]s?(x)`,
`**/*.test.?([cm])[jt]s?(x)`, `**/*.test.?([cm])[jt]s?(x)`,
`**/*.bench.?([cm])[jt]s?(x)`, `**/*.bench.?([cm])[jt]s?(x)`,
`**/*.benchmark.?([cm])[jt]s?(x)`, `**/*.benchmark.?([cm])[jt]s?(x)`,
], ],
plugins: { plugins: {
test: { test: {
...pluginTest, ...pluginTest,
rules: { rules: {
...pluginTest.rules, ...pluginTest.rules,
...pluginNoOnlyTests.rules, ...pluginNoOnlyTests.rules,
}, },
}, },
}, },
rules: { rules: {
'no-console': 'off', 'no-console': 'off',
'node/prefer-global/process': 'off', 'node/prefer-global/process': 'off',
'test/consistent-test-it': [ 'test/consistent-test-it': [
'error', 'error',
{ fn: 'it', withinDescribe: 'it' }, { fn: 'it', withinDescribe: 'it' },
], ],
'test/no-identical-title': 'error', 'test/no-identical-title': 'error',
'test/no-import-node-test': 'error', 'test/no-import-node-test': 'error',
'test/no-only-tests': 'error', 'test/no-only-tests': 'error',
'test/prefer-hooks-in-order': 'error', 'test/prefer-hooks-in-order': 'error',
'test/prefer-lowercase-title': 'error', 'test/prefer-lowercase-title': 'error',
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/turbo.ts
说明:Turbo monorepo 相关规则(eslint-config-turbo),用于检查 turbo.json 配置。
要点:
- 该配置通过插件方式集成,插件无需额外规则定义
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function turbo(): Promise<Linter.Config[]> { export async function turbo(): Promise<Linter.Config[]> {
const [pluginTurbo] = await Promise.all([ const [pluginTurbo] = await Promise.all([
interopDefault(import('eslint-config-turbo')), interopDefault(import('eslint-config-turbo')),
] as const); ] as const);
return [ return [
{ {
plugins: { plugins: {
turbo: pluginTurbo, turbo: pluginTurbo,
}, },
}, },
]; ];
} }
/*
eslint-config/src/configs/typescript.ts
说明:TypeScript 相关规则(@typescript-eslint)用于增强类型层面的检查。
要点:
- 使用 parser 与 plugin 提供更严格的类型检查与建议
- 对生成代码或快速迭代目录保留部分放宽项(例如关闭某些严格规则)
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function typescript(): Promise<Linter.Config[]> { export async function typescript(): Promise<Linter.Config[]> {
const [pluginTs, parserTs] = await Promise.all([ const [pluginTs, parserTs] = await Promise.all([
interopDefault(import('@typescript-eslint/eslint-plugin')), interopDefault(import('@typescript-eslint/eslint-plugin')),
interopDefault(import('@typescript-eslint/parser')), interopDefault(import('@typescript-eslint/parser')),
] as const); ] as const);
return [ return [
{ {
files: ['**/*.?([cm])[jt]s?(x)'], files: ['**/*.?([cm])[jt]s?(x)'],
languageOptions: { languageOptions: {
parser: parserTs, parser: parserTs,
parserOptions: { parserOptions: {
createDefaultProgram: false, // 不使用 createDefaultProgram 以避免性能问题,项目使用基于 glob 的 tsconfig
ecmaFeatures: { createDefaultProgram: false,
jsx: true, ecmaFeatures: {
}, jsx: true,
ecmaVersion: 'latest', },
extraFileExtensions: ['.vue'], ecmaVersion: 'latest',
jsxPragma: 'React', extraFileExtensions: ['.vue'],
project: './tsconfig.*.json', jsxPragma: 'React',
sourceType: 'module', project: './tsconfig.*.json',
}, sourceType: 'module',
}, },
plugins: { },
'@typescript-eslint': pluginTs as any, plugins: {
}, '@typescript-eslint': pluginTs as any,
rules: { },
...pluginTs.configs['eslint-recommended']?.overrides?.[0]?.rules, rules: {
...pluginTs.configs.strict?.rules, ...pluginTs.configs['eslint-recommended']?.overrides?.[0]
'@typescript-eslint/ban-ts-comment': [ ?.rules,
'error', ...pluginTs.configs.strict?.rules,
{ // 对 @ts-xxx 注释进行限制:允许带说明的忽略以便在确有必要时记录原因
'ts-check': false, '@typescript-eslint/ban-ts-comment': [
'ts-expect-error': 'allow-with-description', 'error',
'ts-ignore': 'allow-with-description', {
'ts-nocheck': 'allow-with-description', 'ts-check': false,
}, 'ts-expect-error': 'allow-with-description',
], 'ts-ignore': 'allow-with-description',
'ts-nocheck': 'allow-with-description',
},
],
// '@typescript-eslint/consistent-type-definitions': ['warn', 'interface'], // '@typescript-eslint/consistent-type-definitions': ['warn', 'interface'],
'@typescript-eslint/consistent-type-definitions': 'off', // 关闭统一类型定义风格限制,团队可自由选择 interface/type
'@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-empty-function': [ '@typescript-eslint/explicit-module-boundary-types': 'off',
'error', '@typescript-eslint/no-empty-function': [
{ 'error',
allow: ['arrowFunctions', 'functions', 'methods'], {
}, allow: ['arrowFunctions', 'functions', 'methods'],
], },
'@typescript-eslint/no-explicit-any': 'off', ],
'@typescript-eslint/no-namespace': 'off', '@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-non-null-assertion': 'error', '@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/no-unused-expressions': 'off', // 禁止非空断言以避免隐藏潜在的 undefined/null 错误
'@typescript-eslint/no-unused-vars': [ '@typescript-eslint/no-non-null-assertion': 'error',
'error', '@typescript-eslint/no-unused-expressions': 'off',
{ // 忽略以 `_` 开头的未使用变量,用于占位或为接口兼容保留参数
argsIgnorePattern: '^_', '@typescript-eslint/no-unused-vars': [
varsIgnorePattern: '^_', 'error',
}, {
], argsIgnorePattern: '^_',
'@typescript-eslint/no-use-before-define': 'off', varsIgnorePattern: '^_',
'@typescript-eslint/no-var-requires': 'error', },
'unused-imports/no-unused-vars': 'off', ],
}, '@typescript-eslint/no-use-before-define': 'off',
}, // 禁止使用 require,鼓励使用 import,除非在构建/配置脚本中例外
]; '@typescript-eslint/no-var-requires': 'error',
'unused-imports/no-unused-vars': 'off',
},
},
];
} }
/*
eslint-config/src/configs/unicorn.ts
说明:Unicorn 插件提供现代化的 JavaScript 最佳实践建议。
要点:
- 关闭大量规则以避免过度约束(如 filename-case, consistent-destructuring 等)
- 在脚本目录中放宽 process.exit 限制
- 合理保留部分规则(如 prefer-export-from)以提升代码质量
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function unicorn(): Promise<Linter.Config[]> { export async function unicorn(): Promise<Linter.Config[]> {
const [pluginUnicorn] = await Promise.all([ const [pluginUnicorn] = await Promise.all([
interopDefault(import('eslint-plugin-unicorn')), interopDefault(import('eslint-plugin-unicorn')),
] as const); ] as const);
return [ return [
{ {
plugins: { plugins: {
unicorn: pluginUnicorn, unicorn: pluginUnicorn,
}, },
rules: { rules: {
...pluginUnicorn.configs.recommended.rules, ...pluginUnicorn.configs.recommended.rules,
'unicorn/better-regex': 'off', 'unicorn/better-regex': 'off',
'unicorn/consistent-destructuring': 'off', 'unicorn/consistent-destructuring': 'off',
'unicorn/consistent-function-scoping': 'off', 'unicorn/consistent-function-scoping': 'off',
'unicorn/expiring-todo-comments': 'off', 'unicorn/expiring-todo-comments': 'off',
'unicorn/filename-case': 'off', 'unicorn/filename-case': 'off',
'unicorn/import-style': 'off', 'unicorn/import-style': 'off',
'unicorn/no-array-for-each': 'off', 'unicorn/no-array-for-each': 'off',
'unicorn/no-null': 'off', 'unicorn/no-null': 'off',
'unicorn/no-useless-undefined': 'off', 'unicorn/no-useless-undefined': 'off',
'unicorn/prefer-at': 'off', 'unicorn/prefer-at': 'off',
'unicorn/prefer-dom-node-text-content': 'off', 'unicorn/prefer-dom-node-text-content': 'off',
'unicorn/prefer-export-from': ['error', { ignoreUsedVariables: true }], 'unicorn/prefer-export-from': [
'unicorn/prefer-global-this': 'off', 'error',
'unicorn/prefer-top-level-await': 'off', { ignoreUsedVariables: true },
'unicorn/prevent-abbreviations': 'off', ],
}, 'unicorn/prefer-global-this': 'off',
}, 'unicorn/prefer-top-level-await': 'off',
{ 'unicorn/prevent-abbreviations': 'off',
files: [ },
'scripts/**/*.?([cm])[jt]s?(x)', },
'internal/**/*.?([cm])[jt]s?(x)', {
], files: [
rules: { 'scripts/**/*.?([cm])[jt]s?(x)',
'unicorn/no-process-exit': 'off', 'internal/**/*.?([cm])[jt]s?(x)',
}, ],
}, rules: {
]; 'unicorn/no-process-exit': 'off',
},
},
];
} }
/*
eslint-config/src/configs/vue.ts
说明:Vue 相关规则集合,基于 `eslint-plugin-vue` 的推荐/强制集成并做适配。
要点:
- 使用 vue-eslint-parser 解析 .vue 单文件组件
- 合理开启与关闭规则以兼顾一致性与开发体验(例如 template 命名、属性风格)
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { interopDefault } from '../util'; import { interopDefault } from '../util';
export async function vue(): Promise<Linter.Config[]> { export async function vue(): Promise<Linter.Config[]> {
const [pluginVue, parserVue, parserTs] = await Promise.all([ const [pluginVue, parserVue, parserTs] = await Promise.all([
interopDefault(import('eslint-plugin-vue')), interopDefault(import('eslint-plugin-vue')),
interopDefault(import('vue-eslint-parser')), interopDefault(import('vue-eslint-parser')),
interopDefault(import('@typescript-eslint/parser')), interopDefault(import('@typescript-eslint/parser')),
] as const); ] as const);
const flatEssential = pluginVue.configs?.['flat/essential'] || []; const flatEssential = pluginVue.configs?.['flat/essential'] || [];
const flatStronglyRecommended = const flatStronglyRecommended =
pluginVue.configs?.['flat/strongly-recommended'] || []; pluginVue.configs?.['flat/strongly-recommended'] || [];
const flatRecommended = pluginVue.configs?.['flat/recommended'] || []; const flatRecommended = pluginVue.configs?.['flat/recommended'] || [];
return [ return [
...flatEssential, ...flatEssential,
...flatStronglyRecommended, ...flatStronglyRecommended,
...flatRecommended, ...flatRecommended,
{ {
files: ['**/*.vue'], // 针对 .vue 文件的专属规则
languageOptions: { files: ['**/*.vue'],
// globals: { languageOptions: {
// computed: 'readonly', // globals: {
// defineEmits: 'readonly', // computed: 'readonly',
// defineExpose: 'readonly', // defineEmits: 'readonly',
// defineProps: 'readonly', // defineExpose: 'readonly',
// onMounted: 'readonly', // defineProps: 'readonly',
// onUnmounted: 'readonly', // onMounted: 'readonly',
// reactive: 'readonly', // onUnmounted: 'readonly',
// ref: 'readonly', // reactive: 'readonly',
// shallowReactive: 'readonly', // ref: 'readonly',
// shallowRef: 'readonly', // shallowReactive: 'readonly',
// toRef: 'readonly', // shallowRef: 'readonly',
// toRefs: 'readonly', // toRef: 'readonly',
// watch: 'readonly', // toRefs: 'readonly',
// watchEffect: 'readonly', // watch: 'readonly',
// }, // watchEffect: 'readonly',
parser: parserVue, // },
parserOptions: { parser: parserVue,
ecmaFeatures: { parserOptions: {
jsx: true, ecmaFeatures: {
}, jsx: true,
extraFileExtensions: ['.vue'], },
parser: parserTs, extraFileExtensions: ['.vue'],
sourceType: 'module', parser: parserTs,
}, sourceType: 'module',
}, },
plugins: { },
vue: pluginVue, plugins: {
}, vue: pluginVue,
processor: pluginVue.processors?.['.vue'], },
rules: { processor: pluginVue.processors?.['.vue'],
...pluginVue.configs?.base?.rules, rules: {
// 继承插件基础规则
...pluginVue.configs?.base?.rules,
'vue/attribute-hyphenation': [ // 要求模板属性使用连字符风格(一致性),便于在 HTML 中直接识别
'error', 'vue/attribute-hyphenation': [
'always', 'error',
{ 'always',
ignore: [], {
}, ignore: [],
], },
'vue/attributes-order': 'off', ],
'vue/block-order': [ 'vue/attributes-order': 'off',
'error', // 建议文件块顺序,为审阅和查找提供一致的约定
{ 'vue/block-order': [
order: ['script', 'template', 'style'], 'error',
}, {
], order: ['script', 'template', 'style'],
'vue/component-name-in-template-casing': ['error', 'PascalCase'], },
'vue/component-options-name-casing': ['error', 'PascalCase'], ],
'vue/custom-event-name-casing': ['error', 'camelCase'], // 组件在模板中使用 PascalCase 命名,便于组件识别与一致性
'vue/define-macros-order': [ 'vue/component-name-in-template-casing': [
'error', 'error',
{ 'PascalCase',
order: [ ],
'defineOptions', 'vue/component-options-name-casing': ['error', 'PascalCase'],
'defineProps', 'vue/custom-event-name-casing': ['error', 'camelCase'],
'defineEmits', 'vue/define-macros-order': [
'defineSlots', 'error',
], {
}, order: [
], 'defineOptions',
'vue/dot-location': ['error', 'property'], 'defineProps',
'vue/dot-notation': ['error', { allowKeywords: true }], 'defineEmits',
'vue/eqeqeq': ['error', 'smart'], 'defineSlots',
'vue/html-closing-bracket-newline': 'error', ],
'vue/html-indent': 'off', },
// 'vue/html-indent': ['error', 2], ],
'vue/html-quotes': ['error', 'double'], 'vue/dot-location': ['error', 'property'],
'vue/html-self-closing': [ 'vue/dot-notation': ['error', { allowKeywords: true }],
'error', 'vue/eqeqeq': ['error', 'smart'],
{ 'vue/html-closing-bracket-newline': 'error',
html: { 'vue/html-indent': 'off',
component: 'always', 'vue/html-quotes': ['error', 'double'],
normal: 'never', 'vue/html-self-closing': [
void: 'always', 'error',
}, {
math: 'always', html: {
svg: 'always', component: 'always',
}, normal: 'never',
], void: 'always',
'vue/max-attributes-per-line': 'off', },
'vue/multi-word-component-names': 'off', math: 'always',
'vue/multiline-html-element-content-newline': 'error', svg: 'always',
'vue/no-empty-pattern': 'error', },
'vue/no-extra-parens': ['error', 'functions'], ],
'vue/no-irregular-whitespace': 'error', 'vue/max-attributes-per-line': 'off',
'vue/no-loss-of-precision': 'error', 'vue/multi-word-component-names': 'off',
'vue/no-reserved-component-names': 'off', 'vue/multiline-html-element-content-newline': 'error',
'vue/no-restricted-syntax': [ 'vue/no-empty-pattern': 'error',
'error', 'vue/no-extra-parens': ['error', 'functions'],
'DebuggerStatement', 'vue/no-irregular-whitespace': 'error',
'LabeledStatement', 'vue/no-loss-of-precision': 'error',
'WithStatement', 'vue/no-reserved-component-names': 'off',
], 'vue/no-restricted-syntax': [
'vue/no-restricted-v-bind': ['error', '/^v-/'], 'error',
'vue/no-sparse-arrays': 'error', 'DebuggerStatement',
'vue/no-unused-refs': 'error', 'LabeledStatement',
'vue/no-useless-v-bind': 'error', 'WithStatement',
'vue/object-shorthand': [ ],
'error', 'vue/no-restricted-v-bind': ['error', '/^v-/'],
'always', 'vue/no-sparse-arrays': 'error',
{ 'vue/no-unused-refs': 'error',
avoidQuotes: true, 'vue/no-useless-v-bind': 'error',
ignoreConstructors: false, 'vue/object-shorthand': [
}, 'error',
], 'always',
'vue/one-component-per-file': 'error', {
'vue/prefer-import-from-vue': 'error', avoidQuotes: true,
'vue/prefer-separate-static-class': 'error', ignoreConstructors: false,
'vue/prefer-template': 'error', },
'vue/prop-name-casing': ['error', 'camelCase'], ],
'vue/require-default-prop': 'error', 'vue/one-component-per-file': 'error',
'vue/require-explicit-emits': 'error', 'vue/prefer-import-from-vue': 'error',
'vue/require-prop-types': 'off', 'vue/prefer-separate-static-class': 'error',
'vue/singleline-html-element-content-newline': 'off', 'vue/prefer-template': 'error',
'vue/space-infix-ops': 'error', 'vue/prop-name-casing': ['error', 'camelCase'],
'vue/space-unary-ops': ['error', { nonwords: false, words: true }], // 要求 prop 的默认值,减少组件使用时的未定义行为(但生成/自动组件可在 custom-config 中关闭)
'vue/v-on-event-hyphenation': [ 'vue/require-default-prop': 'error',
'error', 'vue/require-explicit-emits': 'error',
'always', 'vue/require-prop-types': 'off',
{ 'vue/singleline-html-element-content-newline': 'off',
autofix: true, 'vue/space-infix-ops': 'error',
ignore: [], 'vue/space-unary-ops': [
}, 'error',
], { nonwords: false, words: true },
}, ],
}, 'vue/v-on-event-hyphenation': [
]; 'error',
'always',
{
autofix: true,
ignore: [],
},
],
},
},
];
} }
/*
eslint-config/src/custom-config.ts
目的:为 monorepo 内不同目录提供定制化的覆盖规则。
关键点:
- 使用 `files` 精准指定规则生效范围,避免对整个仓库产生副作用
- 通过 `no-restricted-imports` 强制包边界,防止错误或循环依赖
- 在构建/配置文件中放宽部分 import 限制(restrictedImportIgnores)以支持工具链需求
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
const restrictedImportIgnores = [ const restrictedImportIgnores = [
'**/vite.config.mts', '**/vite.config.mts',
'**/tailwind.config.mjs', '**/tailwind.config.mjs',
'**/postcss.config.mjs', '**/postcss.config.mjs',
]; ];
const customConfig: Linter.Config[] = [ const customConfig: Linter.Config[] = [
// shadcn-ui 内部组件是自动生成的,不做太多限制 // shadcn-ui 内部组件是自动生成的,不做太多限制
{ {
files: ['packages/@core/ui-kit/shadcn-ui/**/**'], files: ['packages/@core/ui-kit/shadcn-ui/**/**'],
rules: { rules: {
'vue/require-default-prop': 'off', 'vue/require-default-prop': 'off',
}, },
}, },
{ {
files: [ files: [
'apps/**/**', 'apps/**/**',
'packages/effects/**/**', 'packages/effects/**/**',
'packages/utils/**/**', 'packages/utils/**/**',
'packages/types/**/**', 'packages/types/**/**',
'packages/locales/**/**', 'packages/locales/**/**',
], ],
ignores: restrictedImportIgnores, ignores: restrictedImportIgnores,
rules: { rules: {
'perfectionist/sort-interfaces': 'off', 'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-objects': 'off', 'perfectionist/sort-objects': 'off',
}, },
}, },
{ {
files: ['**/**.vue'], files: ['**/**.vue'],
ignores: restrictedImportIgnores, ignores: restrictedImportIgnores,
rules: { rules: {
'perfectionist/sort-objects': 'off', 'perfectionist/sort-objects': 'off',
}, },
}, },
{ {
// apps内部的一些基础规则 // apps内部的一些基础规则
files: ['apps/**/**'], files: ['apps/**/**'],
ignores: restrictedImportIgnores, ignores: restrictedImportIgnores,
rules: { rules: {
'no-restricted-imports': [ 'no-restricted-imports': [
'error', 'error',
{ {
patterns: [ patterns: [
{ {
group: ['#/api/*'], group: ['#/api/*'],
message: message:
'The #/api package cannot be imported, please use the @core package itself', 'The #/api package cannot be imported, please use the @core package itself',
}, },
{ {
group: ['#/layouts/*'], group: ['#/layouts/*'],
message: message:
'The #/layouts package cannot be imported, please use the @core package itself', 'The #/layouts package cannot be imported, please use the @core package itself',
}, },
{ {
group: ['#/locales/*'], group: ['#/locales/*'],
message: message:
'The #/locales package cannot be imported, please use the @core package itself', 'The #/locales package cannot be imported, please use the @core package itself',
}, },
{ {
group: ['#/stores/*'], group: ['#/stores/*'],
message: message:
'The #/stores package cannot be imported, please use the @core package itself', 'The #/stores package cannot be imported, please use the @core package itself',
}, },
], ],
}, },
], ],
'perfectionist/sort-interfaces': 'off', 'perfectionist/sort-interfaces': 'off',
}, },
}, },
{ {
// @core内部组件,不能引入@vben/* 里面的包 // @core内部组件,不能引入@vben/* 里面的包
files: ['packages/@core/**/**'], files: ['packages/@core/**/**'],
ignores: restrictedImportIgnores, ignores: restrictedImportIgnores,
rules: { rules: {
'no-restricted-imports': [ 'no-restricted-imports': [
'error', 'error',
{ {
patterns: [ patterns: [
{ {
group: ['@vben/*'], group: ['@vben/*'],
message: message:
'The @core package cannot import the @vben package, please use the @core package itself', 'The @core package cannot import the @vben package, please use the @core package itself',
}, },
], ],
}, },
], ],
}, },
}, },
{ {
// @core/shared内部组件,不能引入@vben/* 或者 @vben-core/* 里面的包 // @core/shared内部组件,不能引入@vben/* 或者 @vben-core/* 里面的包
files: ['packages/@core/base/**/**'], files: ['packages/@core/base/**/**'],
ignores: restrictedImportIgnores, ignores: restrictedImportIgnores,
rules: { rules: {
'no-restricted-imports': [ 'no-restricted-imports': [
'error', 'error',
{ {
patterns: [ patterns: [
{ {
group: ['@vben/*', '@vben-core/*'], group: ['@vben/*', '@vben-core/*'],
message: message:
'The @vben-core/shared package cannot import the @vben package, please use the @core/shared package itself', 'The @vben-core/shared package cannot import the @vben package, please use the @core/shared package itself',
}, },
], ],
}, },
], ],
}, },
}, },
{ {
// 不能引入@vben/*里面的包 // 不能引入@vben/*里面的包
files: [ files: [
'packages/types/**/**', 'packages/types/**/**',
'packages/utils/**/**', 'packages/utils/**/**',
'packages/icons/**/**', 'packages/icons/**/**',
'packages/constants/**/**', 'packages/constants/**/**',
'packages/styles/**/**', 'packages/styles/**/**',
'packages/stores/**/**', 'packages/stores/**/**',
'packages/preferences/**/**', 'packages/preferences/**/**',
'packages/locales/**/**', 'packages/locales/**/**',
], ],
ignores: restrictedImportIgnores, ignores: restrictedImportIgnores,
rules: { rules: {
'no-restricted-imports': [ 'no-restricted-imports': [
'error', 'error',
{ {
patterns: [ patterns: [
{ {
group: ['@vben/*'], group: ['@vben/*'],
message: message:
'The @vben package cannot be imported, please use the @core package itself', 'The @vben package cannot be imported, please use the @core package itself',
}, },
], ],
}, },
], ],
}, },
}, },
// 后端模拟代码,不需要太多规则 // 后端模拟代码,不需要太多规则
{ {
files: ['apps/backend-mock/**/**', 'docs/**/**'], files: ['apps/backend-mock/**/**', 'docs/**/**'],
rules: { rules: {
'@typescript-eslint/no-extraneous-class': 'off', '@typescript-eslint/no-extraneous-class': 'off',
'n/no-extraneous-import': 'off', 'n/no-extraneous-import': 'off',
'n/prefer-global/buffer': 'off', 'n/prefer-global/buffer': 'off',
'n/prefer-global/process': 'off', 'n/prefer-global/process': 'off',
'no-console': 'off', 'no-console': 'off',
'unicorn/prefer-module': 'off', 'unicorn/prefer-module': 'off',
}, },
}, },
{ {
files: ['**/**/playwright.config.ts'], files: ['**/**/playwright.config.ts'],
rules: { rules: {
'n/prefer-global/buffer': 'off', 'n/prefer-global/buffer': 'off',
'n/prefer-global/process': 'off', 'n/prefer-global/process': 'off',
'no-console': 'off', 'no-console': 'off',
}, },
}, },
{ {
files: ['internal/**/**', 'scripts/**/**'], files: ['internal/**/**', 'scripts/**/**'],
rules: { rules: {
'no-console': 'off', 'no-console': 'off',
}, },
}, },
]; ];
export { customConfig }; export { customConfig };
/*
eslint-config/src/index.ts
目的:按模块化方式组合多个子配置(vue, typescript, prettier 等),并导出最终的 flat config。
关键点:
- 通过异步 `defineConfig` 聚合子模块,保持加载顺序可控
- 将 prettier 放在较早位置以确保格式化规则正确生效
- 支持在外部传入额外 config 以便在不同场景复用
*/
import type { Linter } from 'eslint'; import type { Linter } from 'eslint';
import { import {
command, command,
comments, comments,
disableds, disableds,
ignores, ignores,
importPluginConfig, importPluginConfig,
javascript, javascript,
jsdoc, jsdoc,
jsonc, jsonc,
node, node,
perfectionist, perfectionist,
prettier, prettier,
regexp, regexp,
test, test,
turbo, turbo,
typescript, typescript,
unicorn, unicorn,
vue, vue,
} from './configs'; } from './configs';
import { customConfig } from './custom-config'; import { customConfig } from './custom-config';
type FlatConfig = Linter.Config; type FlatConfig = Linter.Config;
type FlatConfigPromise = type FlatConfigPromise =
| FlatConfig | FlatConfig
| FlatConfig[] | FlatConfig[]
| Promise<FlatConfig> | Promise<FlatConfig>
| Promise<FlatConfig[]>; | Promise<FlatConfig[]>;
async function defineConfig(config: FlatConfig[] = []) { async function defineConfig(config: FlatConfig[] = []) {
const configs: FlatConfigPromise[] = [ const configs: FlatConfigPromise[] = [
vue(), vue(),
javascript(), javascript(),
ignores(), ignores(),
prettier(), prettier(),
typescript(), typescript(),
jsonc(), jsonc(),
disableds(), disableds(),
importPluginConfig(), importPluginConfig(),
node(), node(),
perfectionist(), perfectionist(),
comments(), comments(),
jsdoc(), jsdoc(),
unicorn(), unicorn(),
test(), test(),
regexp(), regexp(),
command(), command(),
turbo(), turbo(),
...customConfig, ...customConfig,
...config, ...config,
]; ];
const resolved = await Promise.all(configs); const resolved = await Promise.all(configs);
return resolved.flat(); return resolved.flat();
} }
export { defineConfig }; export { defineConfig };
/*
prettier-config/index.mjs
目的:统一代码格式化风格供全仓库使用。
关键点:
- 兼容跨平台换行(endOfLine: 'auto')
- 为 Tailwind CSS 启用 class 排序插件,减少样式类无意义变动
- 采用 120 的 printWidth 平衡可读性和紧凑性
说明:如需覆盖特定 package 的格式,可在该 package 下添加 .prettierrc 或覆盖规则。
*/
export default { export default {
endOfLine: 'auto', endOfLine: 'auto',
overrides: [ overrides: [
{ {
files: ['*.json5'], files: ['*.json5'],
options: { options: {
quoteProps: 'preserve', quoteProps: 'preserve',
singleQuote: false, singleQuote: false,
}, },
}, },
], ],
plugins: ['prettier-plugin-tailwindcss'], plugins: ['prettier-plugin-tailwindcss'],
printWidth: 80, printWidth: 120,
proseWrap: 'never', proseWrap: 'never',
semi: true, semi: true,
singleQuote: true, singleQuote: true,
trailingComma: 'all', trailingComma: 'all',
}; };
/*
stylelint-config/index.mjs
目的:为仓库样式(CSS/SCSS/vue style blocks)提供一致的校验与声明顺序规则。
关键点:
- 使用 standard + recess-order 保证声明顺序与基础校验
- 对 .vue/.html/.scss 使用不同的 customSyntax 以正确解析内联样式与 SCSS 特性
- 与 prettier 协同(stylelint-prettier)让 prettier 负责格式化细节
说明:该配置忽略 JS/TS/JSON/MD 等非样式文件;若特定 package 有特殊需求,可以在该 package 内覆写。
*/
export default { export default {
extends: ['stylelint-config-standard', 'stylelint-config-recess-order'], extends: ['stylelint-config-standard', 'stylelint-config-recess-order'],
ignoreFiles: [ ignoreFiles: [
'**/*.js', '**/*.js',
'**/*.jsx', '**/*.jsx',
'**/*.tsx', '**/*.tsx',
'**/*.ts', '**/*.ts',
'**/*.json', '**/*.json',
'**/*.md', '**/*.md',
], ],
overrides: [ overrides: [
{ {
customSyntax: 'postcss-html', customSyntax: 'postcss-html',
files: ['*.(html|vue)', '**/*.(html|vue)'], files: ['*.(html|vue)', '**/*.(html|vue)'],
rules: { rules: {
'selector-pseudo-class-no-unknown': [ 'selector-pseudo-class-no-unknown': [
true, true,
{ {
ignorePseudoClasses: ['global', 'deep'], ignorePseudoClasses: ['global', 'deep'],
}, },
], ],
'selector-pseudo-element-no-unknown': [ 'selector-pseudo-element-no-unknown': [
true, true,
{ {
ignorePseudoElements: ['v-deep', 'v-global', 'v-slotted'], ignorePseudoElements: [
}, 'v-deep',
], 'v-global',
}, 'v-slotted',
}, ],
{ },
customSyntax: 'postcss-scss', ],
extends: [ },
'stylelint-config-recommended-scss', },
'stylelint-config-recommended-vue/scss', {
], customSyntax: 'postcss-scss',
files: ['*.scss', '**/*.scss'], extends: [
}, 'stylelint-config-recommended-scss',
], 'stylelint-config-recommended-vue/scss',
plugins: [ ],
'stylelint-order', files: ['*.scss', '**/*.scss'],
'@stylistic/stylelint-plugin', },
'stylelint-prettier', ],
'stylelint-scss', plugins: [
], 'stylelint-order',
rules: { '@stylistic/stylelint-plugin',
'at-rule-no-deprecated': null, 'stylelint-prettier',
'at-rule-no-unknown': [ 'stylelint-scss',
true, ],
{ rules: {
ignoreAtRules: [ 'at-rule-no-deprecated': null,
'extends', 'at-rule-no-unknown': [
'ignores', true,
'include', {
'mixin', ignoreAtRules: [
'if', 'extends',
'else', 'ignores',
'media', 'include',
'for', 'mixin',
'at-root', 'if',
'tailwind', 'else',
'apply', 'media',
'variants', 'for',
'responsive', 'at-root',
'screen', 'tailwind',
'function', 'apply',
'each', 'variants',
'use', 'responsive',
'forward', 'screen',
'return', 'function',
], 'each',
}, 'use',
], 'forward',
'font-family-no-missing-generic-family-keyword': null, 'return',
'function-no-unknown': null, ],
'import-notation': null, },
'media-feature-range-notation': null, ],
'named-grid-areas-no-invalid': null, 'font-family-no-missing-generic-family-keyword': null,
'no-descending-specificity': null, 'function-no-unknown': null,
'no-empty-source': null, 'import-notation': null,
'order/order': [ 'media-feature-range-notation': null,
[ 'named-grid-areas-no-invalid': null,
'dollar-variables', 'no-descending-specificity': null,
'custom-properties', 'no-empty-source': null,
'at-rules', 'order/order': [
'declarations', [
{ 'dollar-variables',
name: 'supports', 'custom-properties',
type: 'at-rule', 'at-rules',
}, 'declarations',
{ {
name: 'media', name: 'supports',
type: 'at-rule', type: 'at-rule',
}, },
{ {
name: 'include', name: 'media',
type: 'at-rule', type: 'at-rule',
}, },
'rules', {
], name: 'include',
{ severity: 'error' }, type: 'at-rule',
], },
'prettier/prettier': true, 'rules',
'rule-empty-line-before': [ ],
'always', { severity: 'error' },
{ ],
ignore: ['after-comment', 'first-nested'], 'prettier/prettier': true,
}, 'rule-empty-line-before': [
], 'always',
'scss/at-rule-no-unknown': [ {
true, ignore: ['after-comment', 'first-nested'],
{ },
ignoreAtRules: [ ],
'extends', 'scss/at-rule-no-unknown': [
'ignores', true,
'include', {
'mixin', ignoreAtRules: [
'if', 'extends',
'else', 'ignores',
'media', 'include',
'for', 'mixin',
'at-root', 'if',
'tailwind', 'else',
'apply', 'media',
'variants', 'for',
'responsive', 'at-root',
'screen', 'tailwind',
'function', 'apply',
'each', 'variants',
'use', 'responsive',
'forward', 'screen',
'return', 'function',
], 'each',
}, 'use',
], 'forward',
'scss/operator-no-newline-after': null, 'return',
'selector-class-pattern': ],
'^(?:(?:o|c|u|t|s|is|has|_|js|qa)-)?[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*(?:__[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?(?:--[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?(?:[.+])?$', },
],
'scss/operator-no-newline-after': null,
'selector-class-pattern':
'^(?:(?:o|c|u|t|s|is|has|_|js|qa)-)?[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*(?:__[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?(?:--[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*)?(?:[.+])?$',
'selector-not-notation': null, 'selector-not-notation': null,
}, },
}; };
...@@ -4,10 +4,10 @@ import type { SetupContext } from 'vue'; ...@@ -4,10 +4,10 @@ import type { SetupContext } from 'vue';
import type { Recordable } from '@vben/types'; import type { Recordable } from '@vben/types';
import type { import type {
JsonViewerAction, JsonViewerAction,
JsonViewerProps, JsonViewerProps,
JsonViewerToggle, JsonViewerToggle,
JsonViewerValue, JsonViewerValue,
} from './types'; } from './types';
import { computed, useAttrs } from 'vue'; import { computed, useAttrs } from 'vue';
...@@ -24,88 +24,88 @@ import JsonBigint from 'json-bigint'; ...@@ -24,88 +24,88 @@ import JsonBigint from 'json-bigint';
defineOptions({ name: 'JsonViewer' }); defineOptions({ name: 'JsonViewer' });
const props = withDefaults(defineProps<JsonViewerProps>(), { const props = withDefaults(defineProps<JsonViewerProps>(), {
expandDepth: 1, expandDepth: 1,
copyable: false, copyable: false,
sort: false, sort: false,
boxed: false, boxed: false,
theme: 'default-json-theme', theme: 'default-json-theme',
expanded: false, expanded: false,
previewMode: false, previewMode: false,
showArrayIndex: true, showArrayIndex: true,
showDoubleQuotes: false, showDoubleQuotes: false,
}); });
const emit = defineEmits<{ const emit = defineEmits<{
click: [event: MouseEvent]; click: [event: MouseEvent];
copied: [event: JsonViewerAction]; copied: [event: JsonViewerAction];
keyClick: [key: string]; keyClick: [key: string];
toggle: [param: JsonViewerToggle]; toggle: [param: JsonViewerToggle];
valueClick: [value: JsonViewerValue]; valueClick: [value: JsonViewerValue];
}>(); }>();
const attrs: SetupContext['attrs'] = useAttrs(); const attrs: SetupContext['attrs'] = useAttrs();
function handleClick(event: MouseEvent) { function handleClick(event: MouseEvent) {
if ( if (
event.target instanceof HTMLElement && event.target instanceof HTMLElement &&
event.target.classList.contains('jv-item') event.target.classList.contains('jv-item')
) { ) {
const pathNode = event.target.closest('.jv-push'); const pathNode = event.target.closest('.jv-push');
if (!pathNode || !pathNode.hasAttribute('path')) { if (!pathNode || !pathNode.hasAttribute('path')) {
return; return;
} }
const param: JsonViewerValue = { const param: JsonViewerValue = {
el: event.target, el: event.target,
path: pathNode.getAttribute('path') || '', path: pathNode.getAttribute('path') || '',
depth: Number(pathNode.getAttribute('depth')) || 0, depth: Number(pathNode.getAttribute('depth')) || 0,
value: event.target.textContent || undefined, value: event.target.textContent || undefined,
}; };
param.value = JSON.parse(param.value); param.value = JSON.parse(param.value);
emit('valueClick', param); emit('valueClick', param);
} }
emit('click', event); emit('click', event);
} }
// 支持显示 bigint 数据,如较长的订单号 // 支持显示 bigint 数据,如较长的订单号
const jsonData = computed<Record<string, any>>(() => { const jsonData = computed<Record<string, any>>(() => {
if (typeof props.value !== 'string') { if (typeof props.value !== 'string') {
return props.value || {}; return props.value || {};
} }
try { try {
return JsonBigint({ storeAsString: true }).parse(props.value); return JsonBigint({ storeAsString: true }).parse(props.value);
} catch (error) { } catch (error) {
console.error('JSON parse error:', error); console.error('JSON parse error:', error);
return {}; return {};
} }
}); });
const bindProps = computed<Recordable<any>>(() => { const bindProps = computed<Recordable<any>>(() => {
const copyable = { const copyable = {
copyText: $t('ui.jsonViewer.copy'), copyText: $t('ui.jsonViewer.copy'),
copiedText: $t('ui.jsonViewer.copied'), copiedText: $t('ui.jsonViewer.copied'),
timeout: 2000, timeout: 2000,
...(isBoolean(props.copyable) ? {} : props.copyable), ...(isBoolean(props.copyable) ? {} : props.copyable),
}; };
return { return {
...props, ...props,
...attrs, ...attrs,
value: jsonData.value, value: jsonData.value,
onCopied: (event: JsonViewerAction) => emit('copied', event), onCopied: (event: JsonViewerAction) => emit('copied', event),
onKeyclick: (key: string) => emit('keyClick', key), onKeyclick: (key: string) => emit('keyClick', key),
onClick: (event: MouseEvent) => handleClick(event), onClick: (event: MouseEvent) => handleClick(event),
copyable: props.copyable ? copyable : false, copyable: props.copyable ? copyable : false,
}; };
}); });
</script> </script>
<template> <template>
<VueJsonViewer v-bind="bindProps"> <VueJsonViewer v-bind="bindProps">
<template #copy="slotProps"> <template #copy="slotProps">
<slot name="copy" v-bind="slotProps"></slot> <slot name="copy" v-bind="slotProps"></slot>
</template> </template>
</VueJsonViewer> </VueJsonViewer>
</template> </template>
<style lang="scss"> <style lang="scss">
@use './style.scss'; @use './style.scss';
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!