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
charset=utf-8
end_of_line=lf
insert_final_newline=true
indent_style=space
indent_size=2
indent_style=tab
indent_size=4
max_line_length = 100
trim_trailing_whitespace = true
quote_type = single
......
......@@ -12,14 +12,14 @@ const logoDark = computed(() => preferences.logo.sourceDark);
</script>
<template>
<AuthPageLayout
:app-name="appName"
:logo="logo"
:logo-dark="logoDark"
:page-description="$t('authentication.pageDesc')"
:page-title="$t('authentication.pageTitle')"
>
<!-- 自定义工具栏 -->
<!-- <template #toolbar></template> -->
</AuthPageLayout>
<AuthPageLayout
:app-name="appName"
:logo="logo"
:logo-dark="logoDark"
:page-description="$t('authentication.pageDesc')"
:page-title="$t('authentication.pageTitle')"
>
<!-- 自定义工具栏 -->
<!-- <template #toolbar></template> -->
</AuthPageLayout>
</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 { getPackagesSync } from '@vben/node-utils';
......@@ -5,149 +17,152 @@ import { getPackagesSync } from '@vben/node-utils';
const { packages } = getPackagesSync();
const allowedScopes = [
...packages.map((pkg) => pkg.packageJson.name),
'project',
'style',
'lint',
'ci',
'dev',
'deploy',
'other',
...packages.map((pkg) => pkg.packageJson.name),
'project',
'style',
'lint',
'ci',
'dev',
'deploy',
'other',
];
// precomputed scope
const scopeComplete = execSync('git status --porcelain || true')
.toString()
.trim()
.split('\n')
.find((r) => ~r.indexOf('M src'))
?.replaceAll(/(\/)/g, '%%')
?.match(/src%%((\w|-)*)/)?.[1]
?.replace(/s$/, '');
.toString()
.trim()
.split('\n')
.find((r) => ~r.indexOf('M src'))
?.replaceAll(/(\/)/g, '%%')
?.match(/src%%((\w|-)*)/)?.[1]
?.replace(/s$/, '');
/**
* @type {import('cz-git').UserConfig}
*/
const userConfig = {
extends: ['@commitlint/config-conventional'],
plugins: ['commitlint-plugin-function-rules'],
prompt: {
/** @use `pnpm commit :f` */
alias: {
b: 'build: bump dependencies',
c: 'chore: update config',
f: 'docs: fix typos',
r: 'docs: update README',
s: 'style: update code format',
},
allowCustomIssuePrefixs: false,
// scopes: [...scopes, 'mock'],
allowEmptyIssuePrefixs: false,
customScopesAlign: scopeComplete ? 'bottom' : 'top',
defaultScope: scopeComplete,
// English
typesAppend: [
{ name: 'workflow: workflow improvements', value: 'workflow' },
{ name: 'types: type definition file changes', value: 'types' },
],
extends: ['@commitlint/config-conventional'],
plugins: ['commitlint-plugin-function-rules'],
prompt: {
/** @use `pnpm commit :f` */
alias: {
b: 'build: bump dependencies',
c: 'chore: update config',
f: 'docs: fix typos',
r: 'docs: update README',
s: 'style: update code format',
},
allowCustomIssuePrefixs: false,
// scopes: [...scopes, 'mock'],
allowEmptyIssuePrefixs: false,
customScopesAlign: scopeComplete ? 'bottom' : 'top',
defaultScope: scopeComplete,
// English
typesAppend: [
{ name: 'workflow: workflow improvements', value: 'workflow' },
{ name: 'types: type definition file changes', value: 'types' },
],
// 中英文对照版
// messages: {
// type: '选择你要提交的类型 :',
// scope: '选择一个提交范围 (可选):',
// customScope: '请输入自定义的提交范围 :',
// subject: '填写简短精炼的变更描述 :\n',
// body: '填写更加详细的变更描述 (可选)。使用 "|" 换行 :\n',
// breaking: '列举非兼容性重大的变更 (可选)。使用 "|" 换行 :\n',
// footerPrefixsSelect: '选择关联issue前缀 (可选):',
// customFooterPrefixs: '输入自定义issue前缀 :',
// footer: '列举关联issue (可选) 例如: #31, #I3244 :\n',
// confirmCommit: '是否提交或修改commit ?',
// },
// types: [
// { value: 'feat', name: 'feat: 新增功能' },
// { value: 'fix', name: 'fix: 修复缺陷' },
// { value: 'docs', name: 'docs: 文档变更' },
// { value: 'style', name: 'style: 代码格式' },
// { value: 'refactor', name: 'refactor: 代码重构' },
// { value: 'perf', name: 'perf: 性能优化' },
// { value: 'test', name: 'test: 添加疏漏测试或已有测试改动' },
// { value: 'build', name: 'build: 构建流程、外部依赖变更 (如升级 npm 包、修改打包配置等)' },
// { value: 'ci', name: 'ci: 修改 CI 配置、脚本' },
// { value: 'revert', name: 'revert: 回滚 commit' },
// { value: 'chore', name: 'chore: 对构建过程或辅助工具和库的更改 (不影响源文件、测试用例)' },
// { value: 'wip', name: 'wip: 正在开发中' },
// { value: 'workflow', name: 'workflow: 工作流程改进' },
// { value: 'types', name: 'types: 类型定义文件修改' },
// ],
// emptyScopesAlias: 'empty: 不填写',
// customScopesAlias: 'custom: 自定义',
},
rules: {
/**
* type[scope]: [function] description
*
* ^^^^^^^^^^^^^^ empty line.
* - Something here
*/
'body-leading-blank': [2, 'always'],
/**
* type[scope]: [function] description
*
* - something here
*
* ^^^^^^^^^^^^^^
*/
'footer-leading-blank': [1, 'always'],
/**
* type[scope]: [function] description
* ^^^^^
*/
'function-rules/scope-enum': [
2, // level: error
'always',
(parsed) => {
if (!parsed.scope || allowedScopes.includes(parsed.scope)) {
return [true];
}
// 中英文对照版
// messages: {
// type: '选择你要提交的类型 :',
// scope: '选择一个提交范围 (可选):',
// customScope: '请输入自定义的提交范围 :',
// subject: '填写简短精炼的变更描述 :\n',
// body: '填写更加详细的变更描述 (可选)。使用 "|" 换行 :\n',
// breaking: '列举非兼容性重大的变更 (可选)。使用 "|" 换行 :\n',
// footerPrefixsSelect: '选择关联issue前缀 (可选):',
// customFooterPrefixs: '输入自定义issue前缀 :',
// footer: '列举关联issue (可选) 例如: #31, #I3244 :\n',
// confirmCommit: '是否提交或修改commit ?',
// },
// types: [
// { value: 'feat', name: 'feat: 新增功能' },
// { value: 'fix', name: 'fix: 修复缺陷' },
// { value: 'docs', name: 'docs: 文档变更' },
// { value: 'style', name: 'style: 代码格式' },
// { value: 'refactor', name: 'refactor: 代码重构' },
// { value: 'perf', name: 'perf: 性能优化' },
// { value: 'test', name: 'test: 添加疏漏测试或已有测试改动' },
// { value: 'build', name: 'build: 构建流程、外部依赖变更 (如升级 npm 包、修改打包配置等)' },
// { value: 'ci', name: 'ci: 修改 CI 配置、脚本' },
// { value: 'revert', name: 'revert: 回滚 commit' },
// { value: 'chore', name: 'chore: 对构建过程或辅助工具和库的更改 (不影响源文件、测试用例)' },
// { value: 'wip', name: 'wip: 正在开发中' },
// { value: 'workflow', name: 'workflow: 工作流程改进' },
// { value: 'types', name: 'types: 类型定义文件修改' },
// ],
// emptyScopesAlias: 'empty: 不填写',
// customScopesAlias: 'custom: 自定义',
},
rules: {
/**
* type[scope]: [function] description
*
* ^^^^^^^^^^^^^^ empty line.
* - Something here
*/
'body-leading-blank': [2, 'always'],
/**
* type[scope]: [function] description
*
* - something here
*
* ^^^^^^^^^^^^^^
*/
'footer-leading-blank': [1, 'always'],
/**
* type[scope]: [function] description
* ^^^^^
*/
'function-rules/scope-enum': [
2, // level: error
'always',
(parsed) => {
if (!parsed.scope || allowedScopes.includes(parsed.scope)) {
return [true];
}
return [false, `scope must be one of ${allowedScopes.join(', ')}`];
},
],
/**
* type[scope]: [function] description [No more than 108 characters]
* ^^^^^
*/
'header-max-length': [2, 'always', 108],
return [
false,
`scope must be one of ${allowedScopes.join(', ')}`,
];
},
],
/**
* type[scope]: [function] description [No more than 108 characters]
* ^^^^^
*/
'header-max-length': [2, 'always', 108],
'scope-enum': [0],
'subject-case': [0],
'subject-empty': [2, 'never'],
'type-empty': [2, 'never'],
/**
* type[scope]: [function] description
* ^^^^
*/
'type-enum': [
2,
'always',
[
'feat',
'fix',
'perf',
'style',
'docs',
'test',
'refactor',
'build',
'ci',
'chore',
'revert',
'types',
'release',
],
],
},
'scope-enum': [0],
'subject-case': [0],
'subject-empty': [2, 'never'],
'type-empty': [2, 'never'],
/**
* type[scope]: [function] description
* ^^^^
*/
'type-enum': [
2,
'always',
[
'feat',
'fix',
'perf',
'style',
'docs',
'test',
'refactor',
'build',
'ci',
'chore',
'revert',
'types',
'release',
],
],
},
};
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';
export async function command() {
return [
{
...createCommand(),
},
];
return [
{
...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 { interopDefault } from '../util';
export async function comments(): Promise<Linter.Config[]> {
const [pluginComments] = await Promise.all([
// @ts-expect-error - no types
interopDefault(import('eslint-plugin-eslint-comments')),
] as const);
const [pluginComments] = await Promise.all([
// @ts-expect-error - no types
interopDefault(import('eslint-plugin-eslint-comments')),
] as const);
return [
{
plugins: {
'eslint-comments': pluginComments,
},
rules: {
'eslint-comments/no-aggregating-enable': 'error',
'eslint-comments/no-duplicate-disable': 'error',
'eslint-comments/no-unlimited-disable': 'error',
'eslint-comments/no-unused-enable': 'error',
},
},
];
return [
{
plugins: {
'eslint-comments': pluginComments,
},
rules: {
'eslint-comments/no-aggregating-enable': 'error',
'eslint-comments/no-duplicate-disable': 'error',
'eslint-comments/no-unlimited-disable': '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';
export async function disableds(): Promise<Linter.Config[]> {
return [
{
files: ['**/__tests__/**/*.?([cm])[jt]s?(x)'],
name: 'disables/test',
rules: {
'@typescript-eslint/ban-ts-comment': 'off',
'no-console': 'off',
},
},
{
files: ['**/*.d.ts'],
name: 'disables/dts',
rules: {
'@typescript-eslint/triple-slash-reference': 'off',
},
},
{
files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
name: 'disables/js',
rules: {
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
},
];
return [
{
files: ['**/__tests__/**/*.?([cm])[jt]s?(x)'],
name: 'disables/test',
rules: {
'@typescript-eslint/ban-ts-comment': 'off',
'no-console': 'off',
},
},
{
files: ['**/*.d.ts'],
name: 'disables/dts',
rules: {
'@typescript-eslint/triple-slash-reference': 'off',
},
},
{
files: ['**/*.js', '**/*.mjs', '**/*.cjs'],
name: 'disables/js',
rules: {
'@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';
export async function ignores(): Promise<Linter.Config[]> {
return [
{
ignores: [
'**/node_modules',
'**/dist',
'**/dist-*',
'**/*-dist',
'**/.husky',
'**/.nitro',
'**/.output',
'**/Dockerfile',
'**/package-lock.json',
'**/yarn.lock',
'**/pnpm-lock.yaml',
'**/bun.lockb',
'**/output',
'**/coverage',
'**/temp',
'**/.temp',
'**/tmp',
'**/.tmp',
'**/.history',
'**/.turbo',
'**/.nuxt',
'**/.next',
'**/.vercel',
'**/.changeset',
'**/.idea',
'**/.cache',
'**/.output',
'**/.vite-inspect',
return [
{
ignores: [
'**/node_modules',
'**/dist',
'**/dist-*',
'**/*-dist',
'**/.husky',
'**/.nitro',
'**/.output',
'**/Dockerfile',
'**/package-lock.json',
'**/yarn.lock',
'**/pnpm-lock.yaml',
'**/bun.lockb',
'**/output',
'**/coverage',
'**/temp',
'**/.temp',
'**/tmp',
'**/.tmp',
'**/.history',
'**/.turbo',
'**/.nuxt',
'**/.next',
'**/.vercel',
'**/.changeset',
'**/.idea',
'**/.cache',
'**/.output',
'**/.vite-inspect',
'**/CHANGELOG*.md',
'**/*.min.*',
'**/LICENSE*',
'**/__snapshots__',
'**/*.snap',
'**/fixtures/**',
'**/.vitepress/cache/**',
'**/auto-import?(s).d.ts',
'**/components.d.ts',
'**/vite.config.mts.*',
'**/*.sh',
'**/*.ttf',
'**/*.woff',
],
},
];
'**/CHANGELOG*.md',
'**/*.min.*',
'**/LICENSE*',
'**/__snapshots__',
'**/*.snap',
'**/fixtures/**',
'**/.vitepress/cache/**',
'**/auto-import?(s).d.ts',
'**/components.d.ts',
'**/vite.config.mts.*',
'**/*.sh',
'**/*.ttf',
'**/*.woff',
],
},
];
}
/*
eslint-config/src/configs/import.ts
说明:import 插件用于规整模块导入风格与检查可能的错误导入。
要点:
- 强制 import 顺序/风格以提升可读性
- 在 monorepo 场景下对 `import/no-unresolved` 适度关闭以兼容工作区解析
*/
import type { Linter } from 'eslint';
import * as pluginImport from 'eslint-plugin-import-x';
export async function importPluginConfig(): Promise<Linter.Config[]> {
return [
{
plugins: {
// @ts-expect-error - This is a dynamic import
import: pluginImport,
},
rules: {
'import/consistent-type-specifier-style': ['error', 'prefer-top-level'],
'import/first': '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',
'import/no-unresolved': 'off',
'import/no-webpack-loader-syntax': 'error',
},
},
];
return [
{
plugins: {
// @ts-expect-error - This is a dynamic import
import: pluginImport,
},
rules: {
// 优先在顶层位置声明类型导出,减少嵌套导致的类型混淆
'import/consistent-type-specifier-style': [
'error',
'prefer-top-level',
],
// 导入应集中在文件顶部
'import/first': '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';
export * from './typescript';
export * from './unicorn';
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 { interopDefault } from '../util';
export async function jsdoc(): Promise<Linter.Config[]> {
const [pluginJsdoc] = await Promise.all([
interopDefault(import('eslint-plugin-jsdoc')),
] as const);
const [pluginJsdoc] = await Promise.all([
interopDefault(import('eslint-plugin-jsdoc')),
] as const);
return [
{
plugins: {
jsdoc: pluginJsdoc,
},
rules: {
'jsdoc/check-access': 'warn',
'jsdoc/check-param-names': 'warn',
'jsdoc/check-property-names': 'warn',
'jsdoc/check-types': 'warn',
'jsdoc/empty-tags': 'warn',
'jsdoc/implements-on-classes': 'warn',
'jsdoc/no-defaults': 'warn',
'jsdoc/no-multi-asterisks': 'warn',
'jsdoc/require-param-name': 'warn',
'jsdoc/require-property': 'warn',
'jsdoc/require-property-description': 'warn',
'jsdoc/require-property-name': 'warn',
'jsdoc/require-returns-check': 'warn',
'jsdoc/require-returns-description': 'warn',
'jsdoc/require-yields-check': 'warn',
},
},
];
return [
{
plugins: {
jsdoc: pluginJsdoc,
},
rules: {
'jsdoc/check-access': 'warn',
'jsdoc/check-param-names': 'warn',
'jsdoc/check-property-names': 'warn',
'jsdoc/check-types': 'warn',
'jsdoc/empty-tags': 'warn',
'jsdoc/implements-on-classes': 'warn',
'jsdoc/no-defaults': 'warn',
'jsdoc/no-multi-asterisks': 'warn',
'jsdoc/require-param-name': 'warn',
'jsdoc/require-property': 'warn',
'jsdoc/require-property-description': 'warn',
'jsdoc/require-property-name': 'warn',
'jsdoc/require-returns-check': 'warn',
'jsdoc/require-returns-description': '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 { interopDefault } from '../util';
export async function node(): Promise<Linter.Config[]> {
const pluginNode = await interopDefault(import('eslint-plugin-n'));
const pluginNode = await interopDefault(import('eslint-plugin-n'));
return [
{
plugins: {
n: pluginNode,
},
rules: {
'n/handle-callback-err': ['error', '^(err|error)$'],
'n/no-deprecated-api': 'error',
'n/no-exports-assign': 'error',
'n/no-extraneous-import': [
'error',
{
allowModules: [
'unbuild',
'@vben/vite-config',
'vitest',
'vite',
'@vue/test-utils',
'@vben/tailwind-config',
'@playwright/test',
],
},
],
'n/no-new-require': 'error',
'n/no-path-concat': 'error',
// 'n/no-unpublished-import': 'off',
'n/no-unsupported-features/es-syntax': [
'error',
{
ignores: [],
version: '>=20.12.0',
},
],
'n/prefer-global/buffer': ['error', 'never'],
// 'n/no-missing-import': 'off',
'n/prefer-global/process': ['error', 'never'],
'n/process-exit-as-throw': 'error',
},
},
{
files: [
'scripts/**/*.?([cm])[jt]s?(x)',
'internal/**/*.?([cm])[jt]s?(x)',
],
rules: {
'n/prefer-global/process': 'off',
},
},
];
return [
{
plugins: {
n: pluginNode,
},
rules: {
'n/handle-callback-err': ['error', '^(err|error)$'],
'n/no-deprecated-api': 'error',
'n/no-exports-assign': 'error',
'n/no-extraneous-import': [
'error',
{
allowModules: [
'unbuild',
'@vben/vite-config',
'vitest',
'vite',
'@vue/test-utils',
'@vben/tailwind-config',
'@playwright/test',
],
},
],
'n/no-new-require': 'error',
'n/no-path-concat': 'error',
// 'n/no-unpublished-import': 'off',
'n/no-unsupported-features/es-syntax': [
'error',
{
ignores: [],
version: '>=20.12.0',
},
],
'n/prefer-global/buffer': ['error', 'never'],
// 'n/no-missing-import': 'off',
'n/prefer-global/process': ['error', 'never'],
'n/process-exit-as-throw': 'error',
},
},
{
files: [
'scripts/**/*.?([cm])[jt]s?(x)',
'internal/**/*.?([cm])[jt]s?(x)',
],
rules: {
'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 { interopDefault } from '../util';
export async function perfectionist(): Promise<Linter.Config[]> {
const perfectionistPlugin = await interopDefault(
import('eslint-plugin-perfectionist'),
);
const perfectionistPlugin = await interopDefault(
import('eslint-plugin-perfectionist'),
);
return [
perfectionistPlugin.configs['recommended-natural'],
{
rules: {
'perfectionist/sort-exports': [
'error',
{
order: 'asc',
type: 'natural',
},
],
'perfectionist/sort-imports': [
'error',
{
customGroups: {
type: {
'vben-core-type': ['^@vben-core/.+'],
'vben-type': ['^@vben/.+'],
'vue-type': ['^vue$', '^vue-.+', '^@vue/.+'],
},
value: {
vben: ['^@vben/.+'],
'vben-core': ['^@vben-core/.+'],
vue: ['^vue$', '^vue-.+', '^@vue/.+'],
},
},
environment: 'node',
groups: [
['external-type', 'builtin-type', 'type'],
'vue-type',
'vben-type',
'vben-core-type',
['parent-type', 'sibling-type', 'index-type'],
['internal-type'],
'builtin',
'vue',
'vben',
'vben-core',
'external',
'internal',
['parent', 'sibling', 'index'],
'side-effect',
'side-effect-style',
'style',
'object',
'unknown',
],
internalPattern: ['^#/.+'],
newlinesBetween: 'always',
order: 'asc',
type: 'natural',
},
],
'perfectionist/sort-modules': 'off',
'perfectionist/sort-named-exports': [
'error',
{
order: 'asc',
type: 'natural',
},
],
'perfectionist/sort-objects': [
'off',
{
customGroups: {
items: 'items',
list: 'list',
children: 'children',
},
groups: ['unknown', 'items', 'list', 'children'],
ignorePattern: ['children'],
order: 'asc',
type: 'natural',
},
],
},
},
];
return [
perfectionistPlugin.configs['recommended-natural'],
{
rules: {
'perfectionist/sort-exports': [
'error',
{
order: 'asc',
type: 'natural',
},
],
'perfectionist/sort-imports': [
'error',
{
customGroups: {
type: {
'vben-core-type': ['^@vben-core/.+'],
'vben-type': ['^@vben/.+'],
'vue-type': ['^vue$', '^vue-.+', '^@vue/.+'],
},
value: {
vben: ['^@vben/.+'],
'vben-core': ['^@vben-core/.+'],
vue: ['^vue$', '^vue-.+', '^@vue/.+'],
},
},
environment: 'node',
groups: [
['external-type', 'builtin-type', 'type'],
'vue-type',
'vben-type',
'vben-core-type',
['parent-type', 'sibling-type', 'index-type'],
['internal-type'],
'builtin',
'vue',
'vben',
'vben-core',
'external',
'internal',
['parent', 'sibling', 'index'],
'side-effect',
'side-effect-style',
'style',
'object',
'unknown',
],
internalPattern: ['^#/.+'],
newlinesBetween: 'always',
order: 'asc',
type: 'natural',
},
],
'perfectionist/sort-modules': 'off',
'perfectionist/sort-named-exports': [
'error',
{
order: 'asc',
type: 'natural',
},
],
'perfectionist/sort-objects': [
'off',
{
customGroups: {
items: 'items',
list: 'list',
children: 'children',
},
groups: ['unknown', 'items', 'list', 'children'],
ignorePattern: ['children'],
order: 'asc',
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 { interopDefault } from '../util';
export async function prettier(): Promise<Linter.Config[]> {
const [pluginPrettier] = await Promise.all([
interopDefault(import('eslint-plugin-prettier')),
] as const);
return [
{
plugins: {
prettier: pluginPrettier,
},
rules: {
'prettier/prettier': 'error',
},
},
];
const [pluginPrettier] = await Promise.all([
interopDefault(import('eslint-plugin-prettier')),
] as const);
return [
{
plugins: {
prettier: pluginPrettier,
},
rules: {
// 由 Prettier 统一负责格式,报告为 error 以在 CI 中强制通过格式检查
'prettier/prettier': 'error',
},
},
];
}
/*
eslint-config/src/configs/regexp.ts
说明:正则表达式安全规则(eslint-plugin-regexp)以防止常见的正则错误。
要点:
- 使用插件推荐配置即可
- 避免性能问题、空字符、多字符重复等常见正则缺陷
*/
import type { Linter } from 'eslint';
import { interopDefault } from '../util';
export async function regexp(): Promise<Linter.Config[]> {
const [pluginRegexp] = await Promise.all([
interopDefault(import('eslint-plugin-regexp')),
] as const);
const [pluginRegexp] = await Promise.all([
interopDefault(import('eslint-plugin-regexp')),
] as const);
return [
{
plugins: {
regexp: pluginRegexp,
},
rules: {
...pluginRegexp.configs.recommended.rules,
},
},
];
return [
{
plugins: {
regexp: pluginRegexp,
},
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 { interopDefault } from '../util';
export async function test(): Promise<Linter.Config[]> {
const [pluginTest, pluginNoOnlyTests] = await Promise.all([
interopDefault(import('eslint-plugin-vitest')),
// @ts-expect-error - no types
interopDefault(import('eslint-plugin-no-only-tests')),
] as const);
const [pluginTest, pluginNoOnlyTests] = await Promise.all([
interopDefault(import('eslint-plugin-vitest')),
// @ts-expect-error - no types
interopDefault(import('eslint-plugin-no-only-tests')),
] as const);
return [
{
files: [
`**/__tests__/**/*.?([cm])[jt]s?(x)`,
`**/*.spec.?([cm])[jt]s?(x)`,
`**/*.test.?([cm])[jt]s?(x)`,
`**/*.bench.?([cm])[jt]s?(x)`,
`**/*.benchmark.?([cm])[jt]s?(x)`,
],
plugins: {
test: {
...pluginTest,
rules: {
...pluginTest.rules,
...pluginNoOnlyTests.rules,
},
},
},
rules: {
'no-console': 'off',
'node/prefer-global/process': 'off',
'test/consistent-test-it': [
'error',
{ fn: 'it', withinDescribe: 'it' },
],
'test/no-identical-title': 'error',
'test/no-import-node-test': 'error',
'test/no-only-tests': 'error',
'test/prefer-hooks-in-order': 'error',
'test/prefer-lowercase-title': 'error',
},
},
];
return [
{
files: [
`**/__tests__/**/*.?([cm])[jt]s?(x)`,
`**/*.spec.?([cm])[jt]s?(x)`,
`**/*.test.?([cm])[jt]s?(x)`,
`**/*.bench.?([cm])[jt]s?(x)`,
`**/*.benchmark.?([cm])[jt]s?(x)`,
],
plugins: {
test: {
...pluginTest,
rules: {
...pluginTest.rules,
...pluginNoOnlyTests.rules,
},
},
},
rules: {
'no-console': 'off',
'node/prefer-global/process': 'off',
'test/consistent-test-it': [
'error',
{ fn: 'it', withinDescribe: 'it' },
],
'test/no-identical-title': 'error',
'test/no-import-node-test': 'error',
'test/no-only-tests': 'error',
'test/prefer-hooks-in-order': '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 { interopDefault } from '../util';
export async function turbo(): Promise<Linter.Config[]> {
const [pluginTurbo] = await Promise.all([
interopDefault(import('eslint-config-turbo')),
] as const);
const [pluginTurbo] = await Promise.all([
interopDefault(import('eslint-config-turbo')),
] as const);
return [
{
plugins: {
turbo: pluginTurbo,
},
},
];
return [
{
plugins: {
turbo: pluginTurbo,
},
},
];
}
/*
eslint-config/src/configs/typescript.ts
说明:TypeScript 相关规则(@typescript-eslint)用于增强类型层面的检查。
要点:
- 使用 parser 与 plugin 提供更严格的类型检查与建议
- 对生成代码或快速迭代目录保留部分放宽项(例如关闭某些严格规则)
*/
import type { Linter } from 'eslint';
import { interopDefault } from '../util';
export async function typescript(): Promise<Linter.Config[]> {
const [pluginTs, parserTs] = await Promise.all([
interopDefault(import('@typescript-eslint/eslint-plugin')),
interopDefault(import('@typescript-eslint/parser')),
] as const);
const [pluginTs, parserTs] = await Promise.all([
interopDefault(import('@typescript-eslint/eslint-plugin')),
interopDefault(import('@typescript-eslint/parser')),
] as const);
return [
{
files: ['**/*.?([cm])[jt]s?(x)'],
languageOptions: {
parser: parserTs,
parserOptions: {
createDefaultProgram: false,
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
extraFileExtensions: ['.vue'],
jsxPragma: 'React',
project: './tsconfig.*.json',
sourceType: 'module',
},
},
plugins: {
'@typescript-eslint': pluginTs as any,
},
rules: {
...pluginTs.configs['eslint-recommended']?.overrides?.[0]?.rules,
...pluginTs.configs.strict?.rules,
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-check': false,
'ts-expect-error': 'allow-with-description',
'ts-ignore': 'allow-with-description',
'ts-nocheck': 'allow-with-description',
},
],
return [
{
files: ['**/*.?([cm])[jt]s?(x)'],
languageOptions: {
parser: parserTs,
parserOptions: {
// 不使用 createDefaultProgram 以避免性能问题,项目使用基于 glob 的 tsconfig
createDefaultProgram: false,
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
extraFileExtensions: ['.vue'],
jsxPragma: 'React',
project: './tsconfig.*.json',
sourceType: 'module',
},
},
plugins: {
'@typescript-eslint': pluginTs as any,
},
rules: {
...pluginTs.configs['eslint-recommended']?.overrides?.[0]
?.rules,
...pluginTs.configs.strict?.rules,
// 对 @ts-xxx 注释进行限制:允许带说明的忽略以便在确有必要时记录原因
'@typescript-eslint/ban-ts-comment': [
'error',
{
'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': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-empty-function': [
'error',
{
allow: ['arrowFunctions', 'functions', 'methods'],
},
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-var-requires': 'error',
'unused-imports/no-unused-vars': 'off',
},
},
];
// '@typescript-eslint/consistent-type-definitions': ['warn', 'interface'],
// 关闭统一类型定义风格限制,团队可自由选择 interface/type
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-empty-function': [
'error',
{
allow: ['arrowFunctions', 'functions', 'methods'],
},
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-namespace': 'off',
// 禁止非空断言以避免隐藏潜在的 undefined/null 错误
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-unused-expressions': 'off',
// 忽略以 `_` 开头的未使用变量,用于占位或为接口兼容保留参数
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
'@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 { interopDefault } from '../util';
export async function unicorn(): Promise<Linter.Config[]> {
const [pluginUnicorn] = await Promise.all([
interopDefault(import('eslint-plugin-unicorn')),
] as const);
const [pluginUnicorn] = await Promise.all([
interopDefault(import('eslint-plugin-unicorn')),
] as const);
return [
{
plugins: {
unicorn: pluginUnicorn,
},
rules: {
...pluginUnicorn.configs.recommended.rules,
return [
{
plugins: {
unicorn: pluginUnicorn,
},
rules: {
...pluginUnicorn.configs.recommended.rules,
'unicorn/better-regex': 'off',
'unicorn/consistent-destructuring': 'off',
'unicorn/consistent-function-scoping': 'off',
'unicorn/expiring-todo-comments': 'off',
'unicorn/filename-case': 'off',
'unicorn/import-style': 'off',
'unicorn/no-array-for-each': 'off',
'unicorn/no-null': 'off',
'unicorn/no-useless-undefined': 'off',
'unicorn/prefer-at': 'off',
'unicorn/prefer-dom-node-text-content': 'off',
'unicorn/prefer-export-from': ['error', { ignoreUsedVariables: true }],
'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)',
],
rules: {
'unicorn/no-process-exit': 'off',
},
},
];
'unicorn/better-regex': 'off',
'unicorn/consistent-destructuring': 'off',
'unicorn/consistent-function-scoping': 'off',
'unicorn/expiring-todo-comments': 'off',
'unicorn/filename-case': 'off',
'unicorn/import-style': 'off',
'unicorn/no-array-for-each': 'off',
'unicorn/no-null': 'off',
'unicorn/no-useless-undefined': 'off',
'unicorn/prefer-at': 'off',
'unicorn/prefer-dom-node-text-content': 'off',
'unicorn/prefer-export-from': [
'error',
{ ignoreUsedVariables: true },
],
'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)',
],
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 { interopDefault } from '../util';
export async function vue(): Promise<Linter.Config[]> {
const [pluginVue, parserVue, parserTs] = await Promise.all([
interopDefault(import('eslint-plugin-vue')),
interopDefault(import('vue-eslint-parser')),
interopDefault(import('@typescript-eslint/parser')),
] as const);
const [pluginVue, parserVue, parserTs] = await Promise.all([
interopDefault(import('eslint-plugin-vue')),
interopDefault(import('vue-eslint-parser')),
interopDefault(import('@typescript-eslint/parser')),
] as const);
const flatEssential = pluginVue.configs?.['flat/essential'] || [];
const flatStronglyRecommended =
pluginVue.configs?.['flat/strongly-recommended'] || [];
const flatRecommended = pluginVue.configs?.['flat/recommended'] || [];
const flatEssential = pluginVue.configs?.['flat/essential'] || [];
const flatStronglyRecommended =
pluginVue.configs?.['flat/strongly-recommended'] || [];
const flatRecommended = pluginVue.configs?.['flat/recommended'] || [];
return [
...flatEssential,
...flatStronglyRecommended,
...flatRecommended,
{
files: ['**/*.vue'],
languageOptions: {
// globals: {
// computed: 'readonly',
// defineEmits: 'readonly',
// defineExpose: 'readonly',
// defineProps: 'readonly',
// onMounted: 'readonly',
// onUnmounted: 'readonly',
// reactive: 'readonly',
// ref: 'readonly',
// shallowReactive: 'readonly',
// shallowRef: 'readonly',
// toRef: 'readonly',
// toRefs: 'readonly',
// watch: 'readonly',
// watchEffect: 'readonly',
// },
parser: parserVue,
parserOptions: {
ecmaFeatures: {
jsx: true,
},
extraFileExtensions: ['.vue'],
parser: parserTs,
sourceType: 'module',
},
},
plugins: {
vue: pluginVue,
},
processor: pluginVue.processors?.['.vue'],
rules: {
...pluginVue.configs?.base?.rules,
return [
...flatEssential,
...flatStronglyRecommended,
...flatRecommended,
{
// 针对 .vue 文件的专属规则
files: ['**/*.vue'],
languageOptions: {
// globals: {
// computed: 'readonly',
// defineEmits: 'readonly',
// defineExpose: 'readonly',
// defineProps: 'readonly',
// onMounted: 'readonly',
// onUnmounted: 'readonly',
// reactive: 'readonly',
// ref: 'readonly',
// shallowReactive: 'readonly',
// shallowRef: 'readonly',
// toRef: 'readonly',
// toRefs: 'readonly',
// watch: 'readonly',
// watchEffect: 'readonly',
// },
parser: parserVue,
parserOptions: {
ecmaFeatures: {
jsx: true,
},
extraFileExtensions: ['.vue'],
parser: parserTs,
sourceType: 'module',
},
},
plugins: {
vue: pluginVue,
},
processor: pluginVue.processors?.['.vue'],
rules: {
// 继承插件基础规则
...pluginVue.configs?.base?.rules,
'vue/attribute-hyphenation': [
'error',
'always',
{
ignore: [],
},
],
'vue/attributes-order': 'off',
'vue/block-order': [
'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'],
'vue/define-macros-order': [
'error',
{
order: [
'defineOptions',
'defineProps',
'defineEmits',
'defineSlots',
],
},
],
'vue/dot-location': ['error', 'property'],
'vue/dot-notation': ['error', { allowKeywords: true }],
'vue/eqeqeq': ['error', 'smart'],
'vue/html-closing-bracket-newline': 'error',
'vue/html-indent': 'off',
// 'vue/html-indent': ['error', 2],
'vue/html-quotes': ['error', 'double'],
'vue/html-self-closing': [
'error',
{
html: {
component: 'always',
normal: 'never',
void: 'always',
},
math: 'always',
svg: 'always',
},
],
'vue/max-attributes-per-line': 'off',
'vue/multi-word-component-names': 'off',
'vue/multiline-html-element-content-newline': 'error',
'vue/no-empty-pattern': 'error',
'vue/no-extra-parens': ['error', 'functions'],
'vue/no-irregular-whitespace': 'error',
'vue/no-loss-of-precision': 'error',
'vue/no-reserved-component-names': 'off',
'vue/no-restricted-syntax': [
'error',
'DebuggerStatement',
'LabeledStatement',
'WithStatement',
],
'vue/no-restricted-v-bind': ['error', '/^v-/'],
'vue/no-sparse-arrays': 'error',
'vue/no-unused-refs': 'error',
'vue/no-useless-v-bind': 'error',
'vue/object-shorthand': [
'error',
'always',
{
avoidQuotes: true,
ignoreConstructors: false,
},
],
'vue/one-component-per-file': 'error',
'vue/prefer-import-from-vue': 'error',
'vue/prefer-separate-static-class': 'error',
'vue/prefer-template': 'error',
'vue/prop-name-casing': ['error', 'camelCase'],
'vue/require-default-prop': 'error',
'vue/require-explicit-emits': 'error',
'vue/require-prop-types': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/space-infix-ops': 'error',
'vue/space-unary-ops': ['error', { nonwords: false, words: true }],
'vue/v-on-event-hyphenation': [
'error',
'always',
{
autofix: true,
ignore: [],
},
],
},
},
];
// 要求模板属性使用连字符风格(一致性),便于在 HTML 中直接识别
'vue/attribute-hyphenation': [
'error',
'always',
{
ignore: [],
},
],
'vue/attributes-order': 'off',
// 建议文件块顺序,为审阅和查找提供一致的约定
'vue/block-order': [
'error',
{
order: ['script', 'template', 'style'],
},
],
// 组件在模板中使用 PascalCase 命名,便于组件识别与一致性
'vue/component-name-in-template-casing': [
'error',
'PascalCase',
],
'vue/component-options-name-casing': ['error', 'PascalCase'],
'vue/custom-event-name-casing': ['error', 'camelCase'],
'vue/define-macros-order': [
'error',
{
order: [
'defineOptions',
'defineProps',
'defineEmits',
'defineSlots',
],
},
],
'vue/dot-location': ['error', 'property'],
'vue/dot-notation': ['error', { allowKeywords: true }],
'vue/eqeqeq': ['error', 'smart'],
'vue/html-closing-bracket-newline': 'error',
'vue/html-indent': 'off',
'vue/html-quotes': ['error', 'double'],
'vue/html-self-closing': [
'error',
{
html: {
component: 'always',
normal: 'never',
void: 'always',
},
math: 'always',
svg: 'always',
},
],
'vue/max-attributes-per-line': 'off',
'vue/multi-word-component-names': 'off',
'vue/multiline-html-element-content-newline': 'error',
'vue/no-empty-pattern': 'error',
'vue/no-extra-parens': ['error', 'functions'],
'vue/no-irregular-whitespace': 'error',
'vue/no-loss-of-precision': 'error',
'vue/no-reserved-component-names': 'off',
'vue/no-restricted-syntax': [
'error',
'DebuggerStatement',
'LabeledStatement',
'WithStatement',
],
'vue/no-restricted-v-bind': ['error', '/^v-/'],
'vue/no-sparse-arrays': 'error',
'vue/no-unused-refs': 'error',
'vue/no-useless-v-bind': 'error',
'vue/object-shorthand': [
'error',
'always',
{
avoidQuotes: true,
ignoreConstructors: false,
},
],
'vue/one-component-per-file': 'error',
'vue/prefer-import-from-vue': 'error',
'vue/prefer-separate-static-class': 'error',
'vue/prefer-template': 'error',
'vue/prop-name-casing': ['error', 'camelCase'],
// 要求 prop 的默认值,减少组件使用时的未定义行为(但生成/自动组件可在 custom-config 中关闭)
'vue/require-default-prop': 'error',
'vue/require-explicit-emits': 'error',
'vue/require-prop-types': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/space-infix-ops': 'error',
'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';
const restrictedImportIgnores = [
'**/vite.config.mts',
'**/tailwind.config.mjs',
'**/postcss.config.mjs',
'**/vite.config.mts',
'**/tailwind.config.mjs',
'**/postcss.config.mjs',
];
const customConfig: Linter.Config[] = [
// shadcn-ui 内部组件是自动生成的,不做太多限制
{
files: ['packages/@core/ui-kit/shadcn-ui/**/**'],
rules: {
'vue/require-default-prop': 'off',
},
},
{
files: [
'apps/**/**',
'packages/effects/**/**',
'packages/utils/**/**',
'packages/types/**/**',
'packages/locales/**/**',
],
ignores: restrictedImportIgnores,
rules: {
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-objects': 'off',
},
},
{
files: ['**/**.vue'],
ignores: restrictedImportIgnores,
rules: {
'perfectionist/sort-objects': 'off',
},
},
{
// apps内部的一些基础规则
files: ['apps/**/**'],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['#/api/*'],
message:
'The #/api package cannot be imported, please use the @core package itself',
},
{
group: ['#/layouts/*'],
message:
'The #/layouts package cannot be imported, please use the @core package itself',
},
{
group: ['#/locales/*'],
message:
'The #/locales package cannot be imported, please use the @core package itself',
},
{
group: ['#/stores/*'],
message:
'The #/stores package cannot be imported, please use the @core package itself',
},
],
},
],
'perfectionist/sort-interfaces': 'off',
},
},
{
// @core内部组件,不能引入@vben/* 里面的包
files: ['packages/@core/**/**'],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@vben/*'],
message:
'The @core package cannot import the @vben package, please use the @core package itself',
},
],
},
],
},
},
{
// @core/shared内部组件,不能引入@vben/* 或者 @vben-core/* 里面的包
files: ['packages/@core/base/**/**'],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@vben/*', '@vben-core/*'],
message:
'The @vben-core/shared package cannot import the @vben package, please use the @core/shared package itself',
},
],
},
],
},
},
// shadcn-ui 内部组件是自动生成的,不做太多限制
{
files: ['packages/@core/ui-kit/shadcn-ui/**/**'],
rules: {
'vue/require-default-prop': 'off',
},
},
{
files: [
'apps/**/**',
'packages/effects/**/**',
'packages/utils/**/**',
'packages/types/**/**',
'packages/locales/**/**',
],
ignores: restrictedImportIgnores,
rules: {
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-objects': 'off',
},
},
{
files: ['**/**.vue'],
ignores: restrictedImportIgnores,
rules: {
'perfectionist/sort-objects': 'off',
},
},
{
// apps内部的一些基础规则
files: ['apps/**/**'],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['#/api/*'],
message:
'The #/api package cannot be imported, please use the @core package itself',
},
{
group: ['#/layouts/*'],
message:
'The #/layouts package cannot be imported, please use the @core package itself',
},
{
group: ['#/locales/*'],
message:
'The #/locales package cannot be imported, please use the @core package itself',
},
{
group: ['#/stores/*'],
message:
'The #/stores package cannot be imported, please use the @core package itself',
},
],
},
],
'perfectionist/sort-interfaces': 'off',
},
},
{
// @core内部组件,不能引入@vben/* 里面的包
files: ['packages/@core/**/**'],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@vben/*'],
message:
'The @core package cannot import the @vben package, please use the @core package itself',
},
],
},
],
},
},
{
// @core/shared内部组件,不能引入@vben/* 或者 @vben-core/* 里面的包
files: ['packages/@core/base/**/**'],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@vben/*', '@vben-core/*'],
message:
'The @vben-core/shared package cannot import the @vben package, please use the @core/shared package itself',
},
],
},
],
},
},
{
// 不能引入@vben/*里面的包
files: [
'packages/types/**/**',
'packages/utils/**/**',
'packages/icons/**/**',
'packages/constants/**/**',
'packages/styles/**/**',
'packages/stores/**/**',
'packages/preferences/**/**',
'packages/locales/**/**',
],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@vben/*'],
message:
'The @vben package cannot be imported, please use the @core package itself',
},
],
},
],
},
},
// 后端模拟代码,不需要太多规则
{
files: ['apps/backend-mock/**/**', 'docs/**/**'],
rules: {
'@typescript-eslint/no-extraneous-class': 'off',
'n/no-extraneous-import': 'off',
'n/prefer-global/buffer': 'off',
'n/prefer-global/process': 'off',
'no-console': 'off',
'unicorn/prefer-module': 'off',
},
},
{
files: ['**/**/playwright.config.ts'],
rules: {
'n/prefer-global/buffer': 'off',
'n/prefer-global/process': 'off',
'no-console': 'off',
},
},
{
files: ['internal/**/**', 'scripts/**/**'],
rules: {
'no-console': 'off',
},
},
{
// 不能引入@vben/*里面的包
files: [
'packages/types/**/**',
'packages/utils/**/**',
'packages/icons/**/**',
'packages/constants/**/**',
'packages/styles/**/**',
'packages/stores/**/**',
'packages/preferences/**/**',
'packages/locales/**/**',
],
ignores: restrictedImportIgnores,
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@vben/*'],
message:
'The @vben package cannot be imported, please use the @core package itself',
},
],
},
],
},
},
// 后端模拟代码,不需要太多规则
{
files: ['apps/backend-mock/**/**', 'docs/**/**'],
rules: {
'@typescript-eslint/no-extraneous-class': 'off',
'n/no-extraneous-import': 'off',
'n/prefer-global/buffer': 'off',
'n/prefer-global/process': 'off',
'no-console': 'off',
'unicorn/prefer-module': 'off',
},
},
{
files: ['**/**/playwright.config.ts'],
rules: {
'n/prefer-global/buffer': 'off',
'n/prefer-global/process': 'off',
'no-console': 'off',
},
},
{
files: ['internal/**/**', 'scripts/**/**'],
rules: {
'no-console': 'off',
},
},
];
export { customConfig };
/*
eslint-config/src/index.ts
目的:按模块化方式组合多个子配置(vue, typescript, prettier 等),并导出最终的 flat config。
关键点:
- 通过异步 `defineConfig` 聚合子模块,保持加载顺序可控
- 将 prettier 放在较早位置以确保格式化规则正确生效
- 支持在外部传入额外 config 以便在不同场景复用
*/
import type { Linter } from 'eslint';
import {
command,
comments,
disableds,
ignores,
importPluginConfig,
javascript,
jsdoc,
jsonc,
node,
perfectionist,
prettier,
regexp,
test,
turbo,
typescript,
unicorn,
vue,
command,
comments,
disableds,
ignores,
importPluginConfig,
javascript,
jsdoc,
jsonc,
node,
perfectionist,
prettier,
regexp,
test,
turbo,
typescript,
unicorn,
vue,
} from './configs';
import { customConfig } from './custom-config';
type FlatConfig = Linter.Config;
type FlatConfigPromise =
| FlatConfig
| FlatConfig[]
| Promise<FlatConfig>
| Promise<FlatConfig[]>;
| FlatConfig
| FlatConfig[]
| Promise<FlatConfig>
| Promise<FlatConfig[]>;
async function defineConfig(config: FlatConfig[] = []) {
const configs: FlatConfigPromise[] = [
vue(),
javascript(),
ignores(),
prettier(),
typescript(),
jsonc(),
disableds(),
importPluginConfig(),
node(),
perfectionist(),
comments(),
jsdoc(),
unicorn(),
test(),
regexp(),
command(),
turbo(),
...customConfig,
...config,
];
const resolved = await Promise.all(configs);
return resolved.flat();
const configs: FlatConfigPromise[] = [
vue(),
javascript(),
ignores(),
prettier(),
typescript(),
jsonc(),
disableds(),
importPluginConfig(),
node(),
perfectionist(),
comments(),
jsdoc(),
unicorn(),
test(),
regexp(),
command(),
turbo(),
...customConfig,
...config,
];
const resolved = await Promise.all(configs);
return resolved.flat();
}
export { defineConfig };
/*
prettier-config/index.mjs
目的:统一代码格式化风格供全仓库使用。
关键点:
- 兼容跨平台换行(endOfLine: 'auto')
- 为 Tailwind CSS 启用 class 排序插件,减少样式类无意义变动
- 采用 120 的 printWidth 平衡可读性和紧凑性
说明:如需覆盖特定 package 的格式,可在该 package 下添加 .prettierrc 或覆盖规则。
*/
export default {
endOfLine: 'auto',
overrides: [
{
files: ['*.json5'],
options: {
quoteProps: 'preserve',
singleQuote: false,
},
},
],
plugins: ['prettier-plugin-tailwindcss'],
printWidth: 80,
proseWrap: 'never',
semi: true,
singleQuote: true,
trailingComma: 'all',
endOfLine: 'auto',
overrides: [
{
files: ['*.json5'],
options: {
quoteProps: 'preserve',
singleQuote: false,
},
},
],
plugins: ['prettier-plugin-tailwindcss'],
printWidth: 120,
proseWrap: 'never',
semi: true,
singleQuote: true,
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 {
extends: ['stylelint-config-standard', 'stylelint-config-recess-order'],
ignoreFiles: [
'**/*.js',
'**/*.jsx',
'**/*.tsx',
'**/*.ts',
'**/*.json',
'**/*.md',
],
overrides: [
{
customSyntax: 'postcss-html',
files: ['*.(html|vue)', '**/*.(html|vue)'],
rules: {
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['global', 'deep'],
},
],
'selector-pseudo-element-no-unknown': [
true,
{
ignorePseudoElements: ['v-deep', 'v-global', 'v-slotted'],
},
],
},
},
{
customSyntax: 'postcss-scss',
extends: [
'stylelint-config-recommended-scss',
'stylelint-config-recommended-vue/scss',
],
files: ['*.scss', '**/*.scss'],
},
],
plugins: [
'stylelint-order',
'@stylistic/stylelint-plugin',
'stylelint-prettier',
'stylelint-scss',
],
rules: {
'at-rule-no-deprecated': null,
'at-rule-no-unknown': [
true,
{
ignoreAtRules: [
'extends',
'ignores',
'include',
'mixin',
'if',
'else',
'media',
'for',
'at-root',
'tailwind',
'apply',
'variants',
'responsive',
'screen',
'function',
'each',
'use',
'forward',
'return',
],
},
],
'font-family-no-missing-generic-family-keyword': null,
'function-no-unknown': null,
'import-notation': null,
'media-feature-range-notation': null,
'named-grid-areas-no-invalid': null,
'no-descending-specificity': null,
'no-empty-source': null,
'order/order': [
[
'dollar-variables',
'custom-properties',
'at-rules',
'declarations',
{
name: 'supports',
type: 'at-rule',
},
{
name: 'media',
type: 'at-rule',
},
{
name: 'include',
type: 'at-rule',
},
'rules',
],
{ severity: 'error' },
],
'prettier/prettier': true,
'rule-empty-line-before': [
'always',
{
ignore: ['after-comment', 'first-nested'],
},
],
'scss/at-rule-no-unknown': [
true,
{
ignoreAtRules: [
'extends',
'ignores',
'include',
'mixin',
'if',
'else',
'media',
'for',
'at-root',
'tailwind',
'apply',
'variants',
'responsive',
'screen',
'function',
'each',
'use',
'forward',
'return',
],
},
],
'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]+)*)?(?:[.+])?$',
extends: ['stylelint-config-standard', 'stylelint-config-recess-order'],
ignoreFiles: [
'**/*.js',
'**/*.jsx',
'**/*.tsx',
'**/*.ts',
'**/*.json',
'**/*.md',
],
overrides: [
{
customSyntax: 'postcss-html',
files: ['*.(html|vue)', '**/*.(html|vue)'],
rules: {
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['global', 'deep'],
},
],
'selector-pseudo-element-no-unknown': [
true,
{
ignorePseudoElements: [
'v-deep',
'v-global',
'v-slotted',
],
},
],
},
},
{
customSyntax: 'postcss-scss',
extends: [
'stylelint-config-recommended-scss',
'stylelint-config-recommended-vue/scss',
],
files: ['*.scss', '**/*.scss'],
},
],
plugins: [
'stylelint-order',
'@stylistic/stylelint-plugin',
'stylelint-prettier',
'stylelint-scss',
],
rules: {
'at-rule-no-deprecated': null,
'at-rule-no-unknown': [
true,
{
ignoreAtRules: [
'extends',
'ignores',
'include',
'mixin',
'if',
'else',
'media',
'for',
'at-root',
'tailwind',
'apply',
'variants',
'responsive',
'screen',
'function',
'each',
'use',
'forward',
'return',
],
},
],
'font-family-no-missing-generic-family-keyword': null,
'function-no-unknown': null,
'import-notation': null,
'media-feature-range-notation': null,
'named-grid-areas-no-invalid': null,
'no-descending-specificity': null,
'no-empty-source': null,
'order/order': [
[
'dollar-variables',
'custom-properties',
'at-rules',
'declarations',
{
name: 'supports',
type: 'at-rule',
},
{
name: 'media',
type: 'at-rule',
},
{
name: 'include',
type: 'at-rule',
},
'rules',
],
{ severity: 'error' },
],
'prettier/prettier': true,
'rule-empty-line-before': [
'always',
{
ignore: ['after-comment', 'first-nested'],
},
],
'scss/at-rule-no-unknown': [
true,
{
ignoreAtRules: [
'extends',
'ignores',
'include',
'mixin',
'if',
'else',
'media',
'for',
'at-root',
'tailwind',
'apply',
'variants',
'responsive',
'screen',
'function',
'each',
'use',
'forward',
'return',
],
},
],
'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';
import type { Recordable } from '@vben/types';
import type {
JsonViewerAction,
JsonViewerProps,
JsonViewerToggle,
JsonViewerValue,
JsonViewerAction,
JsonViewerProps,
JsonViewerToggle,
JsonViewerValue,
} from './types';
import { computed, useAttrs } from 'vue';
......@@ -24,88 +24,88 @@ import JsonBigint from 'json-bigint';
defineOptions({ name: 'JsonViewer' });
const props = withDefaults(defineProps<JsonViewerProps>(), {
expandDepth: 1,
copyable: false,
sort: false,
boxed: false,
theme: 'default-json-theme',
expanded: false,
previewMode: false,
showArrayIndex: true,
showDoubleQuotes: false,
expandDepth: 1,
copyable: false,
sort: false,
boxed: false,
theme: 'default-json-theme',
expanded: false,
previewMode: false,
showArrayIndex: true,
showDoubleQuotes: false,
});
const emit = defineEmits<{
click: [event: MouseEvent];
copied: [event: JsonViewerAction];
keyClick: [key: string];
toggle: [param: JsonViewerToggle];
valueClick: [value: JsonViewerValue];
click: [event: MouseEvent];
copied: [event: JsonViewerAction];
keyClick: [key: string];
toggle: [param: JsonViewerToggle];
valueClick: [value: JsonViewerValue];
}>();
const attrs: SetupContext['attrs'] = useAttrs();
function handleClick(event: MouseEvent) {
if (
event.target instanceof HTMLElement &&
event.target.classList.contains('jv-item')
) {
const pathNode = event.target.closest('.jv-push');
if (!pathNode || !pathNode.hasAttribute('path')) {
return;
}
const param: JsonViewerValue = {
el: event.target,
path: pathNode.getAttribute('path') || '',
depth: Number(pathNode.getAttribute('depth')) || 0,
value: event.target.textContent || undefined,
};
param.value = JSON.parse(param.value);
emit('valueClick', param);
}
emit('click', event);
if (
event.target instanceof HTMLElement &&
event.target.classList.contains('jv-item')
) {
const pathNode = event.target.closest('.jv-push');
if (!pathNode || !pathNode.hasAttribute('path')) {
return;
}
const param: JsonViewerValue = {
el: event.target,
path: pathNode.getAttribute('path') || '',
depth: Number(pathNode.getAttribute('depth')) || 0,
value: event.target.textContent || undefined,
};
param.value = JSON.parse(param.value);
emit('valueClick', param);
}
emit('click', event);
}
// 支持显示 bigint 数据,如较长的订单号
const jsonData = computed<Record<string, any>>(() => {
if (typeof props.value !== 'string') {
return props.value || {};
}
try {
return JsonBigint({ storeAsString: true }).parse(props.value);
} catch (error) {
console.error('JSON parse error:', error);
return {};
}
if (typeof props.value !== 'string') {
return props.value || {};
}
try {
return JsonBigint({ storeAsString: true }).parse(props.value);
} catch (error) {
console.error('JSON parse error:', error);
return {};
}
});
const bindProps = computed<Recordable<any>>(() => {
const copyable = {
copyText: $t('ui.jsonViewer.copy'),
copiedText: $t('ui.jsonViewer.copied'),
timeout: 2000,
...(isBoolean(props.copyable) ? {} : props.copyable),
};
return {
...props,
...attrs,
value: jsonData.value,
onCopied: (event: JsonViewerAction) => emit('copied', event),
onKeyclick: (key: string) => emit('keyClick', key),
onClick: (event: MouseEvent) => handleClick(event),
copyable: props.copyable ? copyable : false,
};
const copyable = {
copyText: $t('ui.jsonViewer.copy'),
copiedText: $t('ui.jsonViewer.copied'),
timeout: 2000,
...(isBoolean(props.copyable) ? {} : props.copyable),
};
return {
...props,
...attrs,
value: jsonData.value,
onCopied: (event: JsonViewerAction) => emit('copied', event),
onKeyclick: (key: string) => emit('keyClick', key),
onClick: (event: MouseEvent) => handleClick(event),
copyable: props.copyable ? copyable : false,
};
});
</script>
<template>
<VueJsonViewer v-bind="bindProps">
<template #copy="slotProps">
<slot name="copy" v-bind="slotProps"></slot>
</template>
</VueJsonViewer>
<VueJsonViewer v-bind="bindProps">
<template #copy="slotProps">
<slot name="copy" v-bind="slotProps"></slot>
</template>
</VueJsonViewer>
</template>
<style lang="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!