Commit db258ece by Jaxon

Merge branch 'feature/monorepo-config' into 'master'

Feature/monorepo config 合并到 dev

See merge request !6
2 parents a9810c74 6de93c79
Showing 718 changed files with 1593 additions and 3141 deletions
...@@ -50,20 +50,25 @@ We have a quick list of common questions to get you started engaging with this p ...@@ -50,20 +50,25 @@ We have a quick list of common questions to get you started engaging with this p
你可以在 changeset 摘要中使用以下格式来引用 PR 和 Issue: 你可以在 changeset 摘要中使用以下格式来引用 PR 和 Issue:
**PR 引用**: **PR 引用**:
- `新增功能 #123` - 会自动转换为链接 - `新增功能 #123` - 会自动转换为链接
- `修复问题 pr #123` - 也支持 - `修复问题 pr #123` - 也支持
- `优化性能 #123 #124` - 支持多个 PR - `优化性能 #123 #124` - 支持多个 PR
**Issue 引用**: **Issue 引用**:
- `修复登录问题 fixes #45` - 会自动转换为 Issue 链接 - `修复登录问题 fixes #45` - 会自动转换为 Issue 链接
- `关闭问题 closes #46` - 也支持 - `关闭问题 closes #46` - 也支持
- `解决问题 resolves #47` - 也支持 - `解决问题 resolves #47` - 也支持
**组合使用**: **组合使用**:
``` ```
修复多个问题 fixes #45 和 #46 #123 #124 修复多个问题 fixes #45 和 #46 #123 #124
``` ```
这会被解析为: 这会被解析为:
- `#45`, `#46` 识别为 Issue(因为有 `fixes` 前缀) - `#45`, `#46` 识别为 Issue(因为有 `fixes` 前缀)
- `#123`, `#124` 识别为 PR(单独的 `#` 号码) - `#123`, `#124` 识别为 PR(单独的 `#` 号码)
...@@ -78,21 +83,29 @@ node .changeset/test-changelog.cjs ...@@ -78,21 +83,29 @@ node .changeset/test-changelog.cjs
这会显示各种场景下的 changelog 生成结果。 这会显示各种场景下的 changelog 生成结果。
## 标准提交流程 ## 标准提交流程
```md ```md
# 1. 先暂存要提交的文件 # 1. 先暂存要提交的文件
git add <文件或目录> git add <文件或目录>
# 2. 然后使用规范化提交命令 # 2. 然后使用规范化提交命令
pnpm commit pnpm commit
# 系统会提示你: # 系统会提示你:
# - 选择 type: feat/fix/chore/etc # - 选择 type: feat/fix/chore/etc
# - 选择 scope: scrm-base/micro-app-template/etc # - 选择 scope: scrm-base/micro-app-template/etc
# - 填写描述 # - 填写描述
# 3. (可选)创建 changeset 用于版本发布 # 3. (可选)创建 changeset 用于版本发布
pnpm changeset pnpm changeset
# 4. 推送代码 # 4. 推送代码
git push
git push
``` ```
--- ---
'@venus/venus-agentic-assisant': major "@venus/venus-agentic-assisant": major
'@venus/venus-agentic-base': major "@venus/venus-agentic-base": major
--- ---
修改汽车智能体平台页面布局/功能页面开发 修改汽车智能体平台页面布局/功能页面开发
--- ---
'@venus/venus-agentic-base': major "@venus/venus-agentic-base": major
--- ---
汽车智能体项目微前端基座布局配置等优化 汽车智能体项目微前端基座布局配置等优化
export { default } from '@venus/commitlint-config'; export { default } from "@venus/commitlint-config";
duyia
Userconfig
addwords
noneles
rangestart
compileroptions
lintstagedrc
EPERM
customflags
\ No newline at end of file \ No newline at end of file
...@@ -4,15 +4,14 @@ root = true ...@@ -4,15 +4,14 @@ 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
trim_trailing_whitespace = true trim_trailing_whitespace = true
quote_type = single quote_type = double
[*.{yml,yaml,json}] [*.{yml,yaml,json}]
indent_style = space indent_style = tab
indent_size = 2 indent_size = 4
[*.md] [*.md]
trim_trailing_whitespace = false trim_trailing_whitespace = false
# default onwer
# vben core onwer
# vben team onwer
name: 🐞 Bug Report
description: Report an issue with Vben Admin to help us make it better.
title: "Bug: "
labels: ["bug: pending triage"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
- type: dropdown
id: version
attributes:
label: Version
description: What version of our software are you running?
options:
- Vben Admin V5
- Vben Admin V2
default: 0
validations:
required: true
- type: textarea
id: bug-desc
attributes:
label: Describe the bug?
description: A clear and concise description of what the bug is. If you intend to submit a PR for this issue, tell us in the description. Thanks!
placeholder: Bug Description
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Reproduction
description: Please provide a link to [StackBlitz](https://stackblitz.com/fork/github/vitest-dev/vitest/tree/main/examples/basic?initialPath=__vitest__/) (you can also use [examples](https://github.com/vitest-dev/vitest/tree/main/examples)) or a github repo that can reproduce the problem you ran into. A [minimal reproduction](https://stackoverflow.com/help/minimal-reproducible-example) is required unless you are absolutely sure that the issue is obvious and the provided information is enough to understand the problem. If a report is vague (e.g. just a generic error message) and has no reproduction, it will receive a "needs reproduction" label. If no reproduction is provided after 3 days, it will be auto-closed.
placeholder: Reproduction
validations:
required: true
- type: textarea
id: system-info
attributes:
label: System Info
description: Output of `npx envinfo --system --npmPackages '{vue}' --binaries --browsers`
render: shell
placeholder: System, Binaries, Browsers
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
render: shell
- type: checkboxes
id: terms
attributes:
label: Validations
description: Before submitting the issue, please make sure you do the following
# description: By submitting this issue, you agree to follow our [Code of Conduct](https://example.com).
options:
- label: Read the [docs](https://doc.vben.pro/)
required: true
- label: Ensure the code is up to date. (Some issues have been fixed in the latest version)
required: true
- label: I have searched the [existing issues](https://github.com/vbenjs/vue-vben-admin/issues) and checked that my issue does not duplicate any existing issues.
required: true
- label: Check that this is a concrete bug. For Q&A open a [GitHub Discussion](https://github.com/vbenjs/vue-vben-admin/discussions) or join our [Discord Chat Server](https://discord.gg/8GuAdwDhj6).
required: true
- label: The provided reproduction is a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of the bug.
required: true
name: 📚 Documentation
description: Report an issue with Vben Admin Website to help us make it better.
title: 'Docs: '
labels: [documentation]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this issue!
- type: checkboxes
id: documentation_is
attributes:
label: Documentation is
options:
- label: Missing
- label: Outdated
- label: Confusing
- label: Not sure?
- type: textarea
id: description
attributes:
label: Explain in Detail
description: A clear and concise description of your suggestion. If you intend to submit a PR for this issue, tell us in the description. Thanks!
placeholder: The description of ... page is not clear. I thought it meant ... but it wasn't.
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: Your Suggestion for Changes
validations:
required: true
- type: textarea
id: reproduction-steps
attributes:
label: Steps to reproduce
description: Please provide any reproduction steps that may need to be described. E.g. if it happens only when running the dev or build script make sure it's clear which one to use.
placeholder: Run `pnpm install` followed by `pnpm run docs:dev`
name: ✨ New Feature Proposal
description: Propose a new feature to be added to Vben Admin
title: 'FEATURE: '
labels: ['enhancement: pending triage']
body:
- type: markdown
attributes:
value: |
Thank you for suggesting a feature for our project! Please fill out the information below to help us understand and implement your request!
- type: dropdown
id: version
attributes:
label: Version
description: What version of our software are you running?
options:
- Vben Admin V5
- Vben Admin V2
default: 0
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: A detailed description of the feature request.
placeholder: Please describe the feature you would like to see, and why it would be useful.
validations:
required: true
- type: textarea
id: proposed-solution
attributes:
label: Proposed Solution
description: A clear and concise description of what you want to happen.
placeholder: Describe the solution you'd like to see
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives Considered
description: |
A clear and concise description of any alternative solutions or features you've considered.
placeholder: Describe any alternative solutions or features you've considered
validations:
required: false
- type: input
id: additional-context
attributes:
label: Additional Context
description: Add any other context or screenshots about the feature request here.
placeholder: Any additional information
validations:
required: false
- type: checkboxes
id: checkboxes
attributes:
label: Validations
description: Before submitting the issue, please make sure you do the following
options:
- label: Read the [docs](https://doc.vben.pro/)
required: true
- label: Ensure the code is up to date. (Some issues have been fixed in the latest version)
required: true
- label: I have searched the [existing issues](https://github.com/vbenjs/vue-vben-admin/issues) and checked that my issue does not duplicate any existing issues.
required: true
name: "Setup Node"
description: "Setup node and pnpm"
runs:
using: "composite"
steps:
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: "pnpm"
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v4
name: Setup pnpm cache
if: ${{ github.ref_name == 'main' }}
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- uses: actions/cache/restore@v4
if: ${{ github.ref_name != 'main' }}
with:
path: ${{ env.STORE_PATH }}
key: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
shell: bash
run: pnpm install --frozen-lockfile
## Git 提交信息规范
> 本规范改编自 [Angular 的提交规范](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular)。
#### 快速总结:
提交信息必须匹配以下正则表达式:
```js
/^(revert: )?(feat|fix|docs|style|refactor|perf|test|workflow|build|ci|chore|types|wip): .{1,50}/;
```
#### 示例
出现在 "功能" 标题下的 `dev` 小标题下:
```
feat(dev): add 'comments' option
```
出现在 "Bug 修复" 标题下的 `dev` 小标题下,并链接到 issue #28:
```
fix(dev): fix dev error
close #28
```
出现在 "性能提升" 标题下,以及 "破坏性变更" 中并包含破坏性变更说明:
```
perf(build): remove 'foo' option
BREAKING CHANGE: The 'foo' option has been removed.
```
如果以下提交和提交 `667ecc1` 在同一个发布版本下,它们不会出现在变更日志中。否则,撤销提交会出现在 "撤销" 标题下。
```
revert: feat(compiler): add 'comments' option
This reverts commit 667ecc1654a317a13331b17617d973392f415f02.
```
### 完整信息格式
提交信息由 **标题**、**正文** 和 **页脚** 组成。标题包含 **类型**、**作用域** 和 **主题**:
```
<type>(<scope>): <subject>
<空行>
<body>
<空行>
<footer>
```
**标题** 是必需的,**作用域** 是可选的。
### 撤销
如果提交撤销了之前的提交,应该以 `revert: ` 开头,后跟被撤销提交的标题。在正文中应该写:`This reverts commit <hash>.`,其中 hash 是被撤销提交的 SHA。
### 类型
如果前缀是 `feat`、`fix` 或 `perf`,它将出现在变更日志中。但如果有任何 [BREAKING CHANGE](#footer),提交将始终出现在变更日志中。
其他前缀可自行决定。建议的前缀有 `docs`、`chore`、`style`、`refactor` 和 `test`,用于与变更日志无关的任务。
### 作用域
作用域可以是指定提交更改位置的任何内容。例如 `dev`、`build`、`workflow`、`cli` 等...
### 主题
主题包含对变更的简洁描述:
- 使用祈使句、现在时:"change" 而不是 "changed" 或 "changes"
- 不要大写第一个字母
- 结尾不要加点 (.)
### 正文
与 **主题** 一样,使用祈使句、现在时:"change" 而不是 "changed" 或 "changes"。正文应包括变更的动机,并将其与之前的行为进行对比。
### 页脚
页脚应包含有关 **破坏性变更** 的任何信息,也是引用此提交 **关闭** 的 GitHub 问题的地方。
**破坏性变更** 应以单词 `BREAKING CHANGE:` 开头,后跟空格或两个换行符。提交信息的其余部分用于此说明。
# 防止在不使用模板的情况下创建问题
blank_issues_enabled: false
checkIssueTemplate: true
checkPullRequestTemplate: true
# 对来自仓库首次贡献者的 PR 发布的评论
newPRWelcomeComment: |
💖 感谢你提交这个拉取请求!💖
请耐心等待,我们会尽快回复你。
# 首次用户合并拉取请求时发布的评论
firstPRMergeComment: >
感谢你的贡献!🎉🎉🎉
# 对首次报告的问题发布的评论
newIssueWelcomeComment: >
感谢你提交第一个问题!请确保遵循问题模板,并提供所有信息来帮助开发者!
# *可选* 检查缺乏描述性的默认标题
# 必须全部小写
requestInfoDefaultTitles:
- update readme.md
- updates
# *必需* 回复的评论
requestInfoReplyComment: >
感谢你提交这个问题/PR!如果你能提供更多信息,我们将不胜感激,这样我们可以更有效地分析上下文中的情况。
# Venus 贡献指南
嗨!我们很高兴你有兴趣为 Venus 做出贡献。在提交你的贡献前,请花点时间阅读以下指南:
- [Pull Request 指南](#pull-request-指南)
## 贡献者行为准则
作为本项目的贡献者和维护者,我们承诺尊重所有通过报告问题、发布功能请求、更新文档、提交拉取请求或补丁以及其他活动来做出贡献的人。
我们致力于让每个人的项目参与都成为一次无骚扰的体验,无论其经验水平、性别、性别认同和表达、性取向、残疾、外观、身体大小、种族、年龄或宗教信仰如何。
参与者不可接受的行为示例包括使用性语言或意象、贬低性评论或人身攻击、骚扰、公开或私下骚扰、侮辱或其他不专业行为。
项目维护者有权删除、编辑或拒绝不符合本行为准则的评论、提交、代码、wiki 编辑、问题和其他贡献。不遵守行为准则的项目维护者可能被从项目团队中移除。
## Pull Request 指南
- 从相关分支(例如 main)检出一个话题分支,并针对该分支进行合并。
- 如果添加新功能:
- 提供一个令人信服的理由来添加此功能。理想情况下,你应该先打开一个建议问题并在处理前获得批准。
- 如果修复 Bug:
- 在 PR 中提供 Bug 的详细描述。最好提供实时演示。
- 在处理 PR 时可以有多个小提交 - GitHub 可以在合并前自动压缩它们。
## 开发设置
你需要 [pnpm](https://pnpm.io/)
克隆仓库后,运行:
```bash
# 安装项目依赖
$ pnpm install
# 启动项目
$ pnpm run dev
```
version: 2
updates:
- package-ecosystem: npm
directory: '/'
schedule:
interval: daily
groups:
non-breaking-changes:
update-types: [minor, patch]
- package-ecosystem: github-actions
directory: '/'
schedule:
interval: weekly
groups:
non-breaking-changes:
update-types: [minor, patch]
## 描述
<!-- 请根据需要描述变更。如果这是一个功能或增强,请尽可能详细。如果这是一个 Bug 修复,请链接它修复的问题或详细描述该 Bug。
-->
<!-- 你也可以在这里添加其他背景信息 -->
## 变更类型
请删除不相关的选项。
- [ ] Bug 修复(不破坏现有功能的修复)
- [ ] 新功能(不破坏现有功能的新增功能)
- [ ] 破坏性变更(会导致现有功能无法按预期工作的修复或功能)
- [ ] 此变更需要更新文档
- [ ] 请不要修改 `pnpm-lock.yaml`,除非你引入了新的测试示例。
## 检查清单
> ℹ️ 检查所有复选框 - 这表明你已按照 [贡献指南](contributing.md) 中的规则完成了所有操作。
- [ ] 如果引入新功能,请记录文档。你可以使用 `pnpm run docs:dev` 命令运行文档。
- [ ] 使用 `pnpm test` 运行测试。
- [ ] 变更日志由 PR 名称生成。请确保它以可理解的方式解释你的更改。请在变更集消息前加上 `feat:`、`fix:`、`perf:`、`docs:` 或 `chore:` 前缀。
- [ ] 我的代码遵循本项目的样式指南
- [ ] 我已对自己的代码进行了自我审查
- [ ] 我已对我的代码进行了评论,特别是在难以理解的区域
- [ ] 我已对文档进行了相应的更改
- [ ] 我的更改未生成新的警告
- [ ] 我已添加测试来证明我的修复有效或我的功能正常工作
- [ ] 新的和现有的单元测试在本地通过我的更改
- [ ] 任何依赖的更改都已在下游模块中合并和发布
name-template: 'v$RESOLVED_VERSION'
tag-template: 'v$RESOLVED_VERSION'
version-template: $MAJOR.$MINOR.$PATCH
change-template: '* $TITLE (#$NUMBER) @$AUTHOR'
template: |
# What's Changed
$CHANGES
**Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION
categories:
- title: '🚀 Features'
labels:
- 'feature'
- title: '🐞 Bug Fixes'
labels:
- 'bug'
- title: '📈 Performance & Enhancement'
labels:
- 'perf'
- 'enhancement'
- title: 📝 Documentation
labels:
- 'documentation'
- title: 👻 Maintenance
labels:
- 'chore'
- 'dependencies'
# collapse-after: 12
- title: 🚦 Tests
labels:
- 'tests'
- title: 'Breaking'
label: 'breaking'
version-resolver:
major:
labels:
- 'major'
- 'breaking'
minor:
labels:
- 'minor'
patch:
labels:
- 'feature'
- 'patch'
- 'bug'
- 'maintenance'
- 'docs'
- 'dependencies'
- 'security'
exclude-labels:
- 'skip-changelog'
- 'no-changelog'
- 'changelog'
- 'bump versions'
- 'reverted'
- 'invalid'
titleAndCommits: true
types:
- feat
- fix
- docs
- chore
- style
- refactor
- perf
- test
- build
- ci
- revert
# 描述:在多个操作系统上验证 PR 的构建可行性,确保代码在不同平台上都能正确构建。
name: Build detection
# PR 打开、同步或重新打开时
# 仅针对 main 分支
on:
pull_request_target:
types: [opened, synchronize, reopened]
branches:
- main
env:
HUSKY: "0"
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
# 1. 检查代码
# 2. 检查出 PR 分支
# 3. 设置 Node 环境
# 4. 执行构建 (pnpm run build)
jobs:
post-update:
if: github.repository == 'monorepo/venus'
# if: ${{ github.actor == 'dependabot[bot]' }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os:
- ubuntu-latest
# - macos-latest
- windows-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Checkout out pull request
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh pr checkout ${{ github.event.pull_request.number }}
- name: Setup Node
uses: ./.github/actions/setup-node
- name: Build
run: |
pnpm run build
# https://github.com/changesets/action
name: Changeset version
# 自动管理 monorepo 的版本更新,使用 changesets 工具管理语义化版本。
# 触发条件:
# PR 合并到 main 分支时
# 手动触发 (workflow_dispatch)
on:
workflow_dispatch:
pull_request:
types:
- closed
branches:
- main
permissions:
pull-requests: write
contents: write
env:
CI: true
# 1. 检查代码
# 2. 设置 Node 环境
# 3. 执行版本更新命令 (pnpm run version)
# 4. 创建版本更新 PR
# 5. 自动提交 (chore: bump versions)
jobs:
version:
if: (github.event.pull_request.merged || github.event_name == 'workflow_dispatch') && github.actor != 'dependabot[bot]' && !contains(github.event.head_commit.message, '[skip ci]') && github.repository == 'monorepo/venus'
# if: github.repository == 'vbenjs/vue-vben-admin'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node
uses: ./.github/actions/setup-node
- name: Create Release Pull Request
uses: changesets/action@v1
with:
version: pnpm run version
commit: "chore: bump versions"
title: "chore: bump versions"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
name: CI
# 当推送/合并到 main或releases/*分支时 执行
# 1. 检查代码 (checkout@v4)
# 2. 安装 pnpm
# 3. 设置 Node 环境
# 4. 安装依赖
# 5. 运行测试
# 6. 构建项目
on:
pull_request:
push:
branches:
- main
- "releases/*"
permissions:
contents: read
env:
CI: true
TZ: Asia/Shanghai
jobs:
test:
name: Test
if: github.repository == 'monorepo/venus'
runs-on: ${{ matrix.os }}
strategy:
matrix:
os:
- ubuntu-latest
# - macos-latest
- windows-latest
timeout-minutes: 20
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
run_install: false
- name: Setup Node
uses: ./.github/actions/setup-node
# - name: Check Git version
# run: git --version
# - name: Setup mock Git user
# run: git config --global user.email "you@example.com" && git config --global user.name "Your Name"
- name: Vitest tests
run: pnpm run test:unit
# - name: Upload coverage
# uses: codecov/codecov-action@v4
# with:
# token: ${{ secrets.CODECOV_TOKEN }}
lint:
name: Lint
if: github.repository == 'monorepo/venus'
runs-on: ${{ matrix.os }}
strategy:
matrix:
os:
- ubuntu-latest
# - macos-latest
- windows-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node
uses: ./.github/actions/setup-node
- name: Lint
run: pnpm run lint
check:
name: Check
if: github.repository == 'monorepo/venus'
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
matrix:
os:
- ubuntu-latest
# - macos-latest
- windows-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node
uses: ./.github/actions/setup-node
- name: Typecheck
run: pnpm check:type
# From https://github.com/rhysd/actionlint/blob/main/docs/usage.md#use-actionlint-on-github-actions
- name: Check workflow files
if: runner.os == 'Linux'
run: |
bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)
./actionlint -color -shellcheck=""
ci-ok:
name: CI OK
if: github.repository == 'monorepo/venus'
runs-on: ubuntu-latest
needs: [test, check, lint]
env:
FAILURE: ${{ contains(join(needs.*.result, ','), 'failure') }}
steps:
- name: Check for failure
run: |
echo $FAILURE
if [ "$FAILURE" = "false" ]; then
exit 0
else
exit 1
fi
# 对于大多数项目而言,此工作流文件无需修改,你只需将其提交至代码仓库即可。
# 你也可以根据需要修改此文件,以此覆盖默认的待分析语言集合,或配置自定义查询语句、构建逻辑。
# ******** 注意事项 ********
# 我们已尝试自动检测你代码仓库中的开发语言。请务必检查下方定义的 language 矩阵,确认其包含的 CodeQL 支持语言集准确无误。
# 使用 GitHub CodeQL 对代码进行静态安全分析,检测潜在的代码漏洞和安全问题。
name: "CodeQL"
# 触发条件:
# 推送到 main 分支
# PR 到 main 分支
# 每周日午夜定时运行(0 35 * * 0)
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
schedule:
- cron: "35 0 * * 0"
jobs:
analyze:
name: Analyze (${{ matrix.language }})
if: github.repository == 'monorepo/venus'
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
# security-events: write - 创建安全事件
# packages: read - 读取包
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
# name: Deploy Website on push
# on:
# push:
# branches:
# - main
# jobs:
# deploy-playground-ftp:
# name: Deploy Push Playground Ftp
# if: github.actor != 'dependabot[bot]' && !contains(github.event.head_commit.message, '[skip ci]') && github.repository == 'vbenjs/vue-vben-admin'
# runs-on: ubuntu-latest
# steps:
# - name: Checkout code
# uses: actions/checkout@v4
# with:
# fetch-depth: 0
# - name: Sed Config Base
# shell: bash
# run: |
# sed -i "s#VITE_COMPRESS\s*=.*#VITE_COMPRESS = gzip#g" ./playground/.env.production
# sed -i "s#VITE_PWA\s*=.*#VITE_PWA = true#g" ./playground/.env.production
# cat ./playground/.env.production
# - name: Setup Node
# uses: ./.github/actions/setup-node
# - name: Build
# run: pnpm build:play
# - name: Sync Playground files
# uses: SamKirkland/FTP-Deploy-Action@v4.3.6
# with:
# server: ${{ secrets.PRO_FTP_HOST }}
# username: ${{ secrets.WEB_PLAYGROUND_FTP_ACCOUNT }}
# password: ${{ secrets.WEB_PLAYGROUND_FTP_PWSSWORD }}
# local-dir: ./playground/dist/
# deploy-antd-ftp:
# name: Deploy Push Antd Ftp
# if: github.actor != 'dependabot[bot]' && !contains(github.event.head_commit.message, '[skip ci]') && github.repository == 'vbenjs/vue-vben-admin'
# runs-on: ubuntu-latest
# steps:
# - name: Checkout code
# uses: actions/checkout@v4
# with:
# fetch-depth: 0
# - name: Sed Config Base
# shell: bash
# run: |
# sed -i "s#VITE_COMPRESS\s*=.*#VITE_COMPRESS = gzip#g" ./apps/web-antd/.env.production
# sed -i "s#VITE_PWA\s*=.*#VITE_PWA = true#g" ./apps/web-antd/.env.production
# cat ./apps/web-antd/.env.production
# - name: Setup Node
# uses: ./.github/actions/setup-node
# - name: Build
# run: pnpm run build:antd
# - name: Sync files
# uses: SamKirkland/FTP-Deploy-Action@v4.3.6
# with:
# server: ${{ secrets.PRO_FTP_HOST }}
# username: ${{ secrets.WEB_ANTD_FTP_ACCOUNT }}
# password: ${{ secrets.WEB_ANTD_FTP_PASSWORD }}
# local-dir: ./apps/web-antd/dist/
# rerun-on-failure:
# name: Rerun on failure
# needs:
# - deploy-playground-ftp
# - deploy-docs-ftp
# - deploy-antd-ftp
# - deploy-ele-ftp
# - deploy-naive-ftp
# if: failure() && fromJSON(github.run_attempt) < 10
# runs-on: ubuntu-latest
# steps:
# - name: Retry ${{ fromJSON(github.run_attempt) }} of 10
# env:
# GH_REPO: ${{ github.repository }}
# GH_TOKEN: ${{ github.token }}
# run: gh workflow run rerun.yml -F run_id=${{ github.run_id }}
name: Release Drafter
# 自动生成发布说明(Release Notes),基于 PR 标签和信息。
# 推送到 main 分支时
on:
push:
branches:
- main
permissions:
contents: read
pull-requests: write
# 自动化生成发布说明
# 基于 PR 自动分类更改
# 简化发布流程
jobs:
update_release_draft:
permissions:
# write permission is required to create a github release
contents: write
# write permission is required for autolabeler
# otherwise, read permission is required at least
pull-requests: write
if: github.repository == 'vbenjs/vue-vben-admin'
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@v6
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# # 每天零点运行一次,它会检查所有带有 "need reproduction" 标签的 Issues。如果这些 Issues 在过去的 3 天内没有任何活动,它们将会被自动关闭。这有助于保持 Issue 列表的整洁,并且提醒用户在必要时提供更多的信息。
# name: Issue Close Require
# # 触发条件:每天零点
# on:
# workflow_dispatch:
# schedule:
# - cron: '0 0 * * *'
# permissions:
# pull-requests: write
# contents: write
# issues: write
# jobs:
# close-issues:
# if: github.repository == 'vbenjs/vue-vben-admin'
# runs-on: ubuntu-latest
# steps:
# # 关闭未活动的 Issues
# - name: Close Inactive Issues
# uses: actions/stale@v9
# with:
# days-before-stale: -1 # Issues and PR will never be flagged stale automatically.
# stale-issue-label: needs-reproduction # Label that flags an issue as stale.
# only-labels: needs-reproduction # Only process these issues
# days-before-issue-close: 3
# ignore-updates: true
# remove-stale-when-updated: false
# close-issue-message: This issue was closed because it was open for 3 days without a valid reproduction.
# close-issue-label: closed-by-action
# name: Label Based Actions
# on:
# issues:
# types: [labeled]
# # pull_request:
# # types: [labeled]
# permissions:
# issues: write
# pull-requests: write
# contents: write
# jobs:
# reply-labeled:
# if: github.repository == 'vbenjs/vue-vben-admin'
# runs-on: ubuntu-latest
# steps:
# - name: remove enhancement pending
# if: github.event.label.name == 'enhancement'
# uses: actions-cool/issues-helper@v3
# with:
# actions: 'remove-labels'
# token: ${{ secrets.GITHUB_TOKEN }}
# issue-number: ${{ github.event.issue.number }}
# labels: 'enhancement: pending triage'
# - name: remove bug pending
# if: github.event.label.name == 'bug'
# uses: actions-cool/issues-helper@v3
# with:
# actions: 'remove-labels'
# token: ${{ secrets.GITHUB_TOKEN }}
# issue-number: ${{ github.event.issue.number }}
# labels: 'bug: pending triage'
# - name: needs reproduction
# if: github.event.label.name == 'needs reproduction'
# uses: actions-cool/issues-helper@v3
# with:
# actions: 'create-comment, remove-labels'
# token: ${{ secrets.GITHUB_TOKEN }}
# issue-number: ${{ github.event.issue.number }}
# body: |
# Hello @${{ github.event.issue.user.login }}. Please provide the complete reproduction steps and code. Issues labeled by `needs reproduction` will be closed if no activities in 3 days.
# labels: 'bug: pending triage'
# name: Lock Threads
# on:
# schedule:
# - cron: "0 0 * * *"
# workflow_dispatch:
# permissions:
# issues: write
# pull-requests: write
# jobs:
# action:
# if: github.repository == 'vbenjs/vue-vben-admin'
# runs-on: ubuntu-latest
# steps:
# - uses: dessant/lock-threads@v5
# with:
# github-token: ${{ secrets.GITHUB_TOKEN }}
# issue-inactive-days: "14"
# issue-lock-reason: ""
# pr-inactive-days: "30"
# pr-lock-reason: ""
# process-only: "issues, prs"
name: Create Release Tag
# 测版本标签推送事件,触发发布流程。
on:
push:
tags:
- "v*.*.*" # Push events to matching v*, i.e. v1.0, v20.15.10
env:
HUSKY: "0"
permissions:
pull-requests: write
contents: write
# 触发条件:
# 推送版本标签,格式:v*.*.*
# 示例:v1.0.0、v20.15.10
# 1. 检查代码
# 2. 执行构建
# 3. 运行测试
# 4. 创建发布
jobs:
build:
name: Create Release
if: github.repository == 'monorepo/venus'
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20]
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
# - name: Checkout code
# uses: actions/checkout@v4
# with:
# fetch-depth: 0
# - name: Install pnpm
# uses: pnpm/action-setup@v4
# - name: Use Node.js ${{ matrix.node-version }}
# uses: actions/setup-node@v4
# with:
# node-version: ${{ matrix.node-version }}
# cache: "pnpm"
# - name: Install dependencies
# run: pnpm install --frozen-lockfile
# - name: Test and Build
# run: |
# pnpm run test
# pnpm run build
- name: version
id: version
run: |
tag=${GITHUB_REF/refs\/tags\//}
version=${tag#v}
major=${version%%.*}
echo "tag=${tag}" >> $GITHUB_OUTPUT
echo "version=${version}" >> $GITHUB_OUTPUT
echo "major=${major}" >> $GITHUB_OUTPUT
- uses: release-drafter/release-drafter@v6
with:
version: ${{ steps.version.outputs.version }}
publish: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# - name: force update major tag
# run: |
# git tag v${{ steps.version.outputs.major }} ${{ steps.version.outputs.tag }} -f
# git push origin refs/tags/v${{ steps.version.outputs.major }} -f
# - name: Create Release for Tag
# id: release_tag
# uses: ncipollo/release-action@v1
# with:
# token: ${{ secrets.GITHUB_TOKEN }}
# generateReleaseNotes: "true"
# body: |
# > Please refer to [CHANGELOG.md](https://github.com/vbenjs/vue-vben-admin/blob/main/CHANGELOG.md) for details.
# name: Rerun workflow
# on:
# workflow_dispatch:
# inputs:
# run_id:
# description: The workflow id to relanch
# required: true
# jobs:
# rerun:
# runs-on: ubuntu-latest
# steps:
# - name: rerun ${{ inputs.run_id }}
# env:
# GH_REPO: ${{ github.repository }}
# GH_TOKEN: ${{ github.token }}
# run: |
# gh run watch ${{ inputs.run_id }} > /dev/null 2>&1
# gh run rerun ${{ inputs.run_id }} --failed
name: Semantic Pull Request
# 验证 PR 标题是否符合语义化提交规范,确保提交信息的一致性。
# 保证提交信息格式一致
# 便于自动生成 CHANGELOG
# 提高代码库可读性
# 触发条件:
# PR 打开、编辑或同步时
on:
pull_request_target:
types:
- opened
- edited
- synchronize
# 首字母:主体首字母不能大写
# 允许的类型:
jobs:
main:
name: Semantic Pull Request
if: github.repository == 'vbenjs/vue-vben-admin'
runs-on: ubuntu-latest
steps:
- name: Validate PR title
uses: amannn/action-semantic-pull-request@v5
with:
wip: true
subjectPattern: ^(?![A-Z]).+$
subjectPatternError: |
The subject "{subject}" found in the pull request title "{title}"
didn't match the configured pattern. Please ensure that the subject
doesn't start with an uppercase character.
requireScope: false
types: |
fix
feat
docs
style
refactor
perf
test
build
ci
chore
revert
types
release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
name: "Close stale issues"
# 自动关闭长时间无活动的 Issue 和 PR,保持项目的活跃度。
on:
schedule:
- cron: "0 1 * * *"
jobs:
stale:
if: github.repository == 'monorepo/venus'
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days"
stale-pr-message: "This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days"
exempt-issue-labels: "bug,enhancement"
days-before-stale: 60
days-before-close: 7
...@@ -22,6 +22,11 @@ yarn.lock ...@@ -22,6 +22,11 @@ yarn.lock
package-lock.json package-lock.json
.VSCodeCounter .VSCodeCounter
**/backend-mock/data **/backend-mock/data
# 忽略所有子文件夹中的 .git
**/.git
# 保留根仓库 .git
!/.git
# local env files # local env files
.env.local .env.local
......
ports:
- port: 5555
onOpen: open-preview
tasks:
- init: npm i -g corepack && pnpm install
command: pnpm run dev:play
# Husky Git Hooks
本目录包含项目的 Git hooks 配置,用于在不同的 Git 操作阶段自动执行检查。
## 配置的 Hooks
### pre-commit
在提交代码之前执行:
- 运行代码格式化 (`pnpm format`)
- 运行代码检查 (`pnpm lint`)
这确保了所有提交的代码都符合项目的代码规范。
### commit-msg
在提交信息创建后执行:
- 使用 commitlint 检查提交信息格式
这确保了所有提交信息都遵循约定式提交规范。
### pre-push
在推送代码到远程仓库之前执行:
- 运行类型检查 (`pnpm check:type`)
- 运行单元测试 (`pnpm test:unit`)
这确保了推送的代码通过了所有类型检查和测试。
## 如何跳过 Hooks
如果在特殊情况下需要跳过 hooks,可以使用以下命令:
```bash
# 跳过 pre-commit 和 commit-msg hooks
git commit --no-verify -m "commit message"
# 跳过 pre-push hooks
git push --no-verify
```
**注意**: 请谨慎使用 `--no-verify` 选项,它应该只在特殊情况下使用。
## 临时禁用 Husky
如果需要临时禁用 husky,可以设置环境变量:
```bash
# Windows (PowerShell)
$env:HUSKY=0
# Linux/Mac
export HUSKY=0
```
## 自定义 Hooks
如需添加或修改 hooks,直接编辑对应的文件即可。所有的 hook 文件都需要有执行权限。
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 使用 commitlint 检查提交信息格式
npx --no -- commitlint --edit "$1"
# 运行代码格式化
pnpm format
# 运行 lint 检查
pnpm lint
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 运行类型检查
pnpm check:type
# 运行单元测试
pnpm test:unit
export default { export default {
"*.{js,ts,tsx,jsx,vue}": ["prettier --write", "eslint --fix"], "*.{js,jsx,ts,tsx,vue,md}": "pnpm eslint --cache --fix",
"*.{md,json,css,less,scss}": ["prettier --write"] "package.json": "pnpm eslint --cache --fix",
"{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": "pnpm eslint --cache --fix",
"*.{scss,less,styl,html,vue,css,wxss}":"pnpm stylelint --fix --allow-empty-input",
}; };
...@@ -2,17 +2,33 @@ dist ...@@ -2,17 +2,33 @@ dist
dev-dist dev-dist
.local .local
.output.js .output.js
node_modules
.nvmrc .nvmrc
coverage coverage
CODEOWNERS CODEOWNERS
.nitro .nitro
.output .output
**/*.vue
**/*.js
**/*.ts
**/*.jsx
**/*.tsx
**/*.json
**/*.wxs
**/*.svg **/*.svg
**/*.sh **/*.sh
public public
.npmrc .npmrc
*-lock.yaml *-lock.yaml
node_modules
miniprogram_npm
uni_modules
wxcomponents
# 只格式化 wxml
!*.wxml
!*.json
export { default } from '@venus/prettier-config'; export { default } from "@venus/prettier-config";
...@@ -2,3 +2,6 @@ dist ...@@ -2,3 +2,6 @@ dist
public public
__tests__ __tests__
coverage coverage
miniprogram_npm
uni_modules
wxcomponents
...@@ -6,8 +6,8 @@ ...@@ -6,8 +6,8 @@
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
// Visual Studio Code 的官方 Stylelint 扩展 // Visual Studio Code 的官方 Stylelint 扩展
"stylelint.vscode-stylelint", "stylelint.vscode-stylelint",
// 使用 Prettier 的代码格式化程序 // // 使用 Prettier 的代码格式化程序
"esbenp.prettier-vscode", // "esbenp.prettier-vscode",
// 支持 dotenv 文件语法 // 支持 dotenv 文件语法
"mikestead.dotenv", "mikestead.dotenv",
// 源代码的拼写检查器 // 源代码的拼写检查器
......
{
"servers": {
"ESLint": {
"type": "stdio",
"command": "npx",
"args": [
"@eslint/mcp@latest"
]
}
},
"inputs": []
}
{ {
"tailwindCSS.experimental.configFile": "internal/tailwind-config/src/index.ts", "tailwindCSS.experimental.configFile": "internal/tailwind-config/src/index.ts",
"eslint.nodePath": "./node_modules",
// 告诉 ESLint:这是一个 monorepo
"eslint.workingDirectories": [{ "mode": "auto" }],
// 使用 flat config(ESLint v9+ 必需)
"eslint.useFlatConfig": true,
"eslint.useESLintClass": true,
"problems.decorations.enabled": false,
"explorer.compactFolders": false,
"scm.compactFolders": false,
// workbench // workbench
"workbench.list.smoothScrolling": true, "workbench.list.smoothScrolling": true,
"workbench.startupEditor": "newUntitledFile", "workbench.startupEditor": "newUntitledFile",
"workbench.tree.indent": 10, "workbench.tree.indent": 24,
"workbench.editor.highlightModifiedTabs": true, "workbench.editor.highlightModifiedTabs": true,
"workbench.editor.closeOnFileDelete": true, "workbench.editor.closeOnFileDelete": true,
"workbench.editor.limit.enabled": true, "workbench.editor.limit.enabled": true,
...@@ -11,8 +21,9 @@ ...@@ -11,8 +21,9 @@
"workbench.editor.limit.value": 5, "workbench.editor.limit.value": 5,
// editor // editor
"editor.tabSize": 2, "editor.tabSize": 4,
"editor.detectIndentation": false, "editor.detectIndentation": false,
"editor.insertSpaces": false,
"editor.cursorBlinking": "expand", "editor.cursorBlinking": "expand",
"editor.largeFileOptimizations": true, "editor.largeFileOptimizations": true,
"editor.accessibilitySupport": "off", "editor.accessibilitySupport": "off",
...@@ -36,32 +47,44 @@ ...@@ -36,32 +47,44 @@
"source.fixAll.stylelint": "explicit", "source.fixAll.stylelint": "explicit",
"source.organizeImports": "never" "source.organizeImports": "never"
}, },
"editor.defaultFormatter": "esbenp.prettier-vscode", "editor.defaultFormatter": "dbaeumer.vscode-eslint",
"[html]": { "[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[css]": { "[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[scss]": { "[wxss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[javascript]": { "[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[typescript]": { "[less]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"[json]": { "[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[markdown]": { "[markdown]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[jsonc]": { "[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "dbaeumer.vscode-eslint"
}, },
"[vue]": { "[vue]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[wxml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
// extensions // extensions
...@@ -107,19 +130,23 @@ ...@@ -107,19 +130,23 @@
"**/.git/subtree-cache/**": true, "**/.git/subtree-cache/**": true,
"**/.vscode/**": true, "**/.vscode/**": true,
"**/node_modules/**": true, "**/node_modules/**": true,
"**/uni_modules/**": true,
"**/miniprogram_npm/**": true,
"**/tmp/**": true, "**/tmp/**": true,
"**/bower_components/**": true, "**/bower_components/**": true,
"**/dist/**": true, "**/dist/**": true,
"**/yarn.lock": true "**/yarn.lock": true
}, },
"typescript.tsserver.exclude": ["**/node_modules", "**/dist", "**/.turbo"], "typescript.tsserver.exclude": ["**/node_modules", "**/dist", "**/.turbo", "**/uni_modules", "**/miniprogram_npm"],
// search // search
"search.searchEditor.singleClickBehaviour": "peekDefinition", "search.searchEditor.singleClickBehaviour": "peekDefinition",
"search.followSymlinks": false, "search.followSymlinks": false,
// 在使用搜索功能时,将这些文件夹/文件排除在外 // 在使用搜索功能时,将这些文件夹/文件排除在外
"search.exclude": { "search.exclude": {
"**/uni_modules": true,
"**/miniprogram_npm": true,
"**/node_modules": true, "**/node_modules": true,
"**/*.log": true, "**/*.log": true,
"**/*.log*": true, "**/*.log*": true,
...@@ -146,7 +173,7 @@ ...@@ -146,7 +173,7 @@
}, },
"debug.onTaskErrors": "debugAnyway", "debug.onTaskErrors": "debugAnyway",
"diffEditor.ignoreTrimWhitespace": true, "diffEditor.ignoreTrimWhitespace": false,
"npm.packageManager": "pnpm", "npm.packageManager": "pnpm",
"css.validate": false, "css.validate": false,
...@@ -162,9 +189,11 @@ ...@@ -162,9 +189,11 @@
"stylelint.enable": true, "stylelint.enable": true,
"stylelint.packageManager": "pnpm", "stylelint.packageManager": "pnpm",
"stylelint.validate": ["css", "less", "postcss", "scss", "vue"], "stylelint.validate": ["css", "less", "postcss", "scss", "vue", "wxss"],
"stylelint.customSyntax": "postcss-html", "stylelint.snippet": ["css", "less", "postcss", "scss", "vue", "wxss"],
"stylelint.snippet": ["css", "less", "postcss", "scss", "vue"], "stylelint.reportInvalidScopeDisables": true,
"stylelint.reportNeedlessDisables": true,
"stylelint.runtimeEnvironment": "node",
"typescript.inlayHints.enumMemberValues.enabled": true, "typescript.inlayHints.enumMemberValues.enabled": true,
"typescript.preferences.preferTypeOnlyAutoImports": true, "typescript.preferences.preferTypeOnlyAutoImports": true,
...@@ -180,12 +209,13 @@ ...@@ -180,12 +209,13 @@
"markdown", "markdown",
"json", "json",
"jsonc", "jsonc",
"json5" "json5",
"wxml"
], ],
"tailwindCSS.experimental.classRegex": [ "eslint.format.enable": true,
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
], "tailwindCSS.experimental.classRegex": [["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]],
"github.copilot.enable": { "github.copilot.enable": {
"*": true, "*": true,
...@@ -217,25 +247,16 @@ ...@@ -217,25 +247,16 @@
"*.ts": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx, $(capture).d.ts", "*.ts": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx, $(capture).d.ts",
"*.tsx": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx,$(capture).d.ts", "*.tsx": "$(capture).test.ts, $(capture).test.tsx, $(capture).spec.ts, $(capture).spec.tsx,$(capture).d.ts",
"*.env": "$(capture).env.*", "*.env": "$(capture).env.*",
"README.md": "README*,CHANGELOG*,LICENSE,CNAME", "package.json": "pnpm-lock.yaml,pnpm-workspace.yaml,.npmrc,.browserslistrc,.node-version,.tazerc.json",
"package.json": "pnpm-lock.yaml,pnpm-workspace.yaml,.gitattributes,.gitignore,.gitpod.yml,.npmrc,.browserslistrc,.node-version,.git*,.tazerc.json", "eslint.config.mjs": ".editorconfig,.eslintignore,.prettierignore,.stylelintignore,.commitlintrc.*,.prettierrc.*,stylelint.config.*,.lintstagedrc.mjs,cspell.json",
"eslint.config.mjs": ".eslintignore,.prettierignore,.stylelintignore,.commitlintrc.*,.prettierrc.*,stylelint.config.*,.lintstagedrc.mjs,cspell.json,lefthook.yml", ".gitignore": ".gitconfig,.gitattributes",
"tailwind.config.mjs": "postcss.*" "tailwind.config.mjs": "postcss.*"
}, },
"scm.repositories.visible": 0,
"commentTranslate.hover.enabled": false, "commentTranslate.hover.enabled": false,
"commentTranslate.multiLineMerge": true, "commentTranslate.multiLineMerge": true,
"vue.server.hybridMode": true, "vue.server.hybridMode": true,
"typescript.tsdk": "node_modules/typescript/lib", "typescript.tsdk": "node_modules/typescript/lib",
"oxc.enable": false, "oxc.enable": false,
"cSpell.words": [ "cSpell.words": ["archiver", "axios", "dotenv", "isequal", "jspm", "napi", "nolebase", "rollup", "vitest"],
"archiver",
"axios",
"dotenv",
"isequal",
"jspm",
"napi",
"nolebase",
"rollup",
"vitest"
]
} }
MIT License
Copyright (c) 2024-present, venus
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 🔧 快速修复指南
## 问题诊断
✅ **问题已确认**:`@venus/venus-agentic-base` 项目的 vite 依赖符号链接损坏
```
Error: Cannot find module '.../venus-agentic-base/node_modules/vite/bin/vite.js'
```
vite 文件夹存在但是空的!
## 🚀 解决方案(三选一)
### 方案 1:使用修复脚本(推荐,最简单)
在项目根目录执行:
```cmd
fix-dependencies.bat
```
### 方案 2:手动执行命令
```cmd
# 1. 进入问题项目目录
cd apps\frontend\venus-agentic\venus-agentic-base
# 2. 删除 node_modules
rmdir /s /q node_modules
# 3. 返回根目录
cd ..\..\..\..\
# 4. 重新安装所有依赖
pnpm install
```
### 方案 3:只重装问题项目
```cmd
pnpm --filter=@venus/venus-agentic-base install --force
```
## ✅ 验证修复
修复后执行:
```cmd
pnpm dev
```
选择 `@venus/venus-agentic-base`,应该能正常启动。
## 📊 预期结果
启动成功后会看到:
```
VITE v7.x.x ready in xxx ms
➜ Local: http://localhost:8080/
➜ Network: http://192.168.x.x:8080/
```
## 🔍 如果还有问题
### 检查 1:确认 vite 已正确安装
```cmd
cd apps\frontend\venus-agentic\venus-agentic-base\node_modules\vite\bin
dir
```
应该能看到 `vite.js` 文件。
### 检查 2:查看根目录的 vite
```cmd
cd node_modules\.pnpm
dir vite@* /s /b
```
应该能看到 vite 相关的包。
### 检查 3:完全清理重装(终极方案)
```cmd
# 删除所有 node_modules 和 lockfile
pnpm clean
del pnpm-lock.yaml
# 重新安装
pnpm install
```
## ⚠️ 常见原因
1. **pnpm 版本问题** - 升级 pnpm:`corepack use pnpm@latest`
2. **Windows 符号链接权限** - 以管理员身份运行终端
3. **磁盘空间不足** - 清理磁盘空间
4. **杀毒软件干扰** - 临时禁用杀毒软件
5. **路径过长** - 将项目移到较短的路径
## 📝 其他 apps 项目状态
✅ 正常项目:
- @venus/venus-base
- @venus/venus-micro-app
- @venus/docs
❌ 需要修复:
- @venus/venus-agentic-base (当前问题)
- @venus/venus-agentic-assisant (可能也需要检查)
## 💡 预防措施
1. 始终在项目根目录执行 `pnpm install`
2. 不要手动修改 node_modules
3. 使用 `pnpm store prune` 定期清理缓存
4. 提交代码时不要包含 node_modules
Venus
# 方式 1:交互式
pnpm build
# 然后选择 venus-base
# 方式 2:直接指定(最快捷)⭐
pnpm build --filter=venus-base
# 或者使用完整包名
pnpm build --filter=@venus/frontend-micro/venus-base
# 构建所有项目
pnpm build:all
# Scripts 命令文档
本文档说明了 `package.json` 中所有 script 命令的作用。
## 开发相关
### `dev`
启动开发服务器,运行所有包/应用的开发模式。
```bash
pnpm dev
```
### `dev:docs`
启动文档开发服务器。
```bash
pnpm dev:docs
```
### `preview`
预览构建后的应用。
```bash
pnpm preview
```
## 构建相关
### `build`
构建项目(使用 turbo-run,设置内存限制为 8GB)。
```bash
pnpm build
```
### `build:all`
构建所有项目(使用 turbo,设置内存限制为 8GB)。
```bash
pnpm build:all
```
### `build:filter`
按过滤条件构建并复制到根目录。
```bash
pnpm build:filter
```
### `build:docs`
构建文档项目。
```bash
pnpm build:docs
```
## 代码质量检查
### `check`
运行所有检查:循环依赖、依赖、类型检查、拼写检查。
```bash
pnpm check
```
### `check:circular`
检查代码中的循环依赖。
```bash
pnpm check:circular
```
### `check:dep`
检查依赖关系。
```bash
pnpm check:dep
```
### `check:type`
运行 TypeScript 类型检查。
```bash
pnpm check:type
```
### `check:cspell`
对代码和文档进行拼写检查。
```bash
pnpm check:cspell
```
### `lint`
运行 ESLint 代码检查。
```bash
pnpm lint
```
### `format`
格式化代码(自动修复格式问题)。
```bash
pnpm format
```
### `publint`
发布前对包进行 lint 检查。
```bash
pnpm publint
```
## 测试相关
### `test:unit`
运行单元测试(使用 Vitest,DOM 环境)。
```bash
pnpm test:unit
```
### `test:e2e`
运行端到端测试(使用 Playwright)。
```bash
pnpm test:e2e
```
### `command:test`
测试构建命令。
```bash
pnpm command:test
```
## 依赖管理
### `update:deps`
交互式更新所有依赖到最新版本。
```bash
pnpm update:deps
```
### `reinstall`
清理并重新安装依赖(删除锁文件后重新安装)。
```bash
pnpm reinstall
```
### `clean`
清理构建产物和临时文件。
```bash
pnpm clean
```
## 版本管理
### `changeset`
创建变更集(用于版本管理和生成 CHANGELOG)。
```bash
pnpm changeset
```
### `version`
更新版本号并更新锁文件(通常在发布前使用)。
```bash
pnpm version
```
### `catalog`
运行 pnpm catalog codemod(管理依赖目录)。
```bash
pnpm catalog
```
## Venus CLI 相关
### `venus`
运行 Venus CLI 工具。
```bash
pnpm venus
```
### `venus:build`
构建 Venus CLI 工具。
```bash
pnpm venus:build
```
### `venus:create`
创建新的 Venus 项目。
```bash
pnpm venus:create
```
### `venus:create:interactive`
交互式创建新的 Venus 项目。
```bash
pnpm venus:create:interactive
```
### `venus:ls`
列出可用的 Venus 模板。
```bash
pnpm venus:ls
```
## Git 相关
### `commit`
使用 PowerShell 脚本进行 Git 提交(配置了 commitlint)。
```bash
pnpm commit
```
## 生命周期钩子
### `preinstall`
安装前钩子:强制使用 pnpm 作为包管理器。
### `postinstall`
安装后钩子:在所有包中运行 stub 脚本(如果存在)。
### `prepare`
初始化 Husky Git hooks。
console.log("hello world");
// const test = 100;
// const duyia = 1000;
// console.log(duyia);
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"types": ["node"],
"lib": ["ESNext"]
}
}
# 寮€鍙戠幆澧冮厤缃?
# 搴旂敤鍩烘湰淇℃伅
VITE_APP_NAME=寰簲鐢ㄦā鏉?VITE_APP_VERSION=1.0.0
# 寰簲鐢ㄥ悕绉帮紙涓庡熀搴ч厤缃繚鎸佷竴鑷达級
VITE_MICRO_APP_NAME=subapp-vue
# 鏈嶅姟绔彛
VITE_PORT=8081
# API 鍩虹璺緞
VITE_API_BASE_URL=http://localhost:3000/api
VITE_API_TIMEOUT=30000
# 璺敱鍩虹璺緞
VITE_BASE_URL=/subapp-vue
VITE_ROUTER_BASE=/subapp-vue
# 寰簲鐢ㄨ闂矾寰?VITE_PUBLIC_PATH=http://localhost:8081/
# 鏄惁涓哄紑鍙戞ā寮?VITE_USE_DEV_MODE=true
# 鏄惁鍚敤Mock鏁版嵁
VITE_USE_MOCK=false
# 鏄惁鍚敤璋冭瘯妯″紡
VITE_DEBUG=true
# 鍩哄骇搴旂敤鍦板潃
VITE_MAIN_APP_URL=http://localhost:8080
# 鏂囦欢涓婁紶鍦板潃
VITE_UPLOAD_URL=http://localhost:3000/api/upload
# 寮€鍙戠幆澧冩爣璇?NODE_ENV=development
# 鐢熶骇鐜閰嶇疆
# 鐢熶骇鐜鍩虹璺緞
VITE_BASE_URL=/subapp-vue/
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue3 微前端子应用</title>
<meta name="description" content="基于 qiankun + Vue3 + Vite 的微前端子应用模板" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "@venus/venus-agent-assisent",
"version": "1.0.0",
"description": "Vue3 微前端子应用模板,用于与 qiankun 基座集成",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 8081 --host",
"build": "vue-tsc && vite build",
"preview": "vite preview --port 8081",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"@vueuse/core": "catalog:",
"axios": "catalog:",
"pinia": "catalog:",
"vue": "catalog:",
"vue-router": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@vitejs/plugin-vue": "catalog:",
"@vitejs/plugin-vue-jsx": "catalog:",
"typescript": "catalog:",
"unplugin-auto-import": "catalog:",
"unplugin-vue-components": "catalog:",
"vite": "catalog:",
"vite-plugin-qiankun": "catalog:",
"vue-tsc": "catalog:"
}
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
<script setup lang="ts">
import { onMounted } from 'vue';
onMounted(() => {
console.log('Vue3 微应用已挂载');
});
</script>
<template>
<div id="micro-app" class="micro-app-container">
<header class="app-header">
<h1>🚀 Vue3 微前端子应用</h1>
<nav class="nav-menu">
<router-link to="/" class="nav-link">首页</router-link>
<router-link to="/about" class="nav-link">关于</router-link>
<router-link to="/communication" class="nav-link">通信示例</router-link>
<router-link to="/user" class="nav-link">用户管理</router-link>
<router-link to="/settings" class="nav-link">系统设置</router-link>
</nav>
</header>
<main class="app-main">
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</main>
<footer class="app-footer">
<p>© 2025 Venus 微前端子应用模板</p>
</footer>
</div>
</template>
<style scoped>
.micro-app-container {
display: flex;
flex-direction: column;
min-height: 100vh;
color: white;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.app-header {
padding: 1.5rem 2rem;
background: rgb(255 255 255 / 10%);
border-bottom: 1px solid rgb(255 255 255 / 20%);
backdrop-filter: blur(10px);
}
.app-header h1 {
margin: 0 0 1rem;
font-size: 1.8rem;
font-weight: 600;
}
.nav-menu {
display: flex;
gap: 1.5rem;
}
.nav-link {
padding: 0.5rem 1rem;
color: white;
text-decoration: none;
background: rgb(255 255 255 / 10%);
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.nav-link:hover {
background: rgb(255 255 255 / 20%);
transform: translateY(-2px);
}
.nav-link.router-link-active {
font-weight: 600;
background: rgb(255 255 255 / 30%);
}
.app-main {
flex: 1;
padding: 2rem;
}
.app-footer {
padding: 1rem 2rem;
text-align: center;
background: rgb(0 0 0 / 20%);
border-top: 1px solid rgb(255 255 255 / 10%);
}
/* 路由过渡动画 */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper';
import type { App as VueApp } from 'vue';
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import {
qiankunWindow,
renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper';
import App from './App.vue';
import { createRouter } from './router';
import './style.css';
let app: null | VueApp<Element> = null;
let router: any = null;
/**
* 渲染函数
* @param props qiankun 传递的参数
*/
async function render(props: QiankunProps = {}) {
const { container } = props;
app = createApp(App);
// 配置 Pinia
app.use(createPinia());
// 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
? props.routerBase || '/subapp-vue'
: '/';
router = createRouter(routerBase);
app.use(router);
// 初始化通信管理器(仅在 qiankun 环境中)
if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.init(props);
// 将通信管理器挂载到全局属性,方便组件使用
app.config.globalProperties.$communication = subAppCommunication;
}
// 挂载应用
const containerEl = container
? container.querySelector('#app')
: document.querySelector('#app');
if (containerEl) {
app.mount(containerEl as Element);
} else {
console.error('[Vue3 微应用] 挂载容器未找到');
}
}
/**
* 独立运行时
* 直接访问子应用时,不是通过基座加载
*/
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log('独立运行模式');
render();
}
/**
* qiankun 生命周期钩子 - bootstrap
* 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子
*/
export async function bootstrap() {
console.log('[Vue3 微应用] bootstrap');
}
/**
* qiankun 生命周期钩子 - mount
* 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法
*/
export async function mount(props: QiankunProps) {
console.log('Vue3 微应用 mount', props);
render(props);
}
/**
* qiankun 生命周期钩子 - unmount
* 应用每次切出/卸载都会调用 unmount 方法
*/
export async function unmount(props: QiankunProps) {
console.log('[Vue3 微应用] unmount', props);
// 销毁通信管理器
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
const { subAppCommunication } = await import('./utils/communication');
subAppCommunication.destroy();
}
if (app) {
app.unmount();
app = null;
}
if (router) {
router = null;
}
}
/**
* qiankun 生命周期钩子 - update (可选)
* 主应用向子应用下发新的props时触发
*/
export async function update(props: QiankunProps) {
console.log('[Vue3 微应用] update', props);
}
// 使用 vite-plugin-qiankun 提供的渲染函数
renderWithQiankun({
bootstrap,
mount,
unmount,
update,
});
import type { Router, RouteRecordRaw } from 'vue-router';
import { createRouter as _createRouter, createWebHistory } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: '首页',
},
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue'),
meta: {
title: '关于',
},
},
{
path: '/user',
name: 'User',
component: () => import('@/views/User.vue'),
meta: {
title: '用户管理',
},
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/Settings.vue'),
meta: {
title: '系统设置',
},
},
{
path: '/communication',
name: 'Communication',
component: () => import('@/views/Communication.vue'),
meta: {
title: '通信示例',
},
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue'),
},
];
/**
* 创建路由实例
* @param base 路由 base 路径
*/
export function createRouter(base: string = '/'): Router {
const router = _createRouter({
history: createWebHistory(base),
routes,
});
// 路由守卫
router.beforeEach((to, _from, next) => {
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - Vue3 微应用`;
}
next();
});
router.afterEach((to, from) => {
console.log('[Vue3 微应用] 路由切换:', from.path, '->', to.path);
});
return router;
}
/* 全局样式 */
* {
box-sizing: border-box;
}
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
font-weight: 400;
line-height: 1.5;
color-scheme: light dark;
font-synthesis: none;
text-rendering: optimizelegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
body {
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
margin: 0;
}
#app {
width: 100%;
min-height: 100vh;
}
/* 滚动条样式 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: rgb(255 255 255 / 10%);
}
::-webkit-scrollbar-thumb {
background: rgb(255 255 255 / 30%);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgb(255 255 255 / 50%);
}
/* 选中文本样式 */
::selection {
color: white;
background: rgb(255 255 255 / 30%);
}
/* 响应式 */
@media (max-width: 768px) {
body {
font-size: 14px;
}
}
import { onUnmounted } from 'vue';
/**
* 全局状态接口定义(与基座保持一致)
*/
export interface GlobalState {
config: {
apiBaseUrl: string;
timeout: number;
};
notifications: Notification[];
theme: {
mode: 'dark' | 'light';
primaryColor: string;
};
user: null | {
avatar: string;
id: string;
name: string;
permissions: string[];
role: string;
};
}
/**
* 通知消息接口
*/
export interface Notification {
from?: string;
id: string;
message: string;
timestamp: number;
title: string;
type: 'error' | 'info' | 'success' | 'warning';
}
/**
* qiankun Props 类型定义
*/
export interface QiankunProps {
[key: string]: any;
container?: HTMLElement;
onGlobalStateChange?: (
callback: (state: GlobalState, prev: GlobalState) => void,
fireImmediately?: boolean,
) => void;
routerBase?: string;
setGlobalState?: (state: Partial<GlobalState>) => void;
}
/**
* 子应用通信管理器
*/
class SubAppCommunicationManager {
private currentState: GlobalState | null = null; // 缓存当前状态
private listeners: Array<(state: GlobalState, prev: GlobalState) => void> =
[];
private props: null | QiankunProps = null;
private unsubscribe: (() => void) | null = null;
/**
* 销毁
*/
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
this.listeners = [];
this.props = null;
console.log('[子应用通信] 通信管理器已销毁');
}
/**
* 获取当前全局状态
*/
getCurrentState(): GlobalState | null {
return this.currentState;
}
/**
* 初始化通信管理器
* @param props qiankun 传递的 props
*/
init(props: QiankunProps) {
this.props = props;
// 监听全局状态变化
if (props.onGlobalStateChange) {
const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => {
console.log('[子应用通信] 全局状态变化:', state, prev);
// 缓存当前状态
this.currentState = state;
// 触发所有监听器
this.listeners.forEach((listener) => {
listener(state, prev);
});
},
true, // 立即触发,获取当前状态 - 这确保了微应用一加载就能获取主应用的数据
);
// 只在返回值是函数时才赋值
if (typeof unsubscribeFn === 'function') {
this.unsubscribe = unsubscribeFn;
}
}
console.log('[子应用通信] 通信管理器初始化完成');
// 额外的保险措施:延迟一点再触发一次所有监听器,确保数据已经传递
setTimeout(() => {
if (this.props?.onGlobalStateChange) {
console.log('[子应用通信] 二次确认全局状态同步');
}
}, 100);
}
/**
* 监听全局状态变化
* @param callback 回调函数
* @returns 取消监听的函数
*/
onStateChange(
callback: (state: GlobalState, prev: GlobalState) => void,
): () => void {
this.listeners.push(callback);
// 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) {
console.log('[子应用通信] 立即触发回调,使用缓存的全局状态');
callback(this.currentState, {} as GlobalState);
}
return () => {
const index = this.listeners.indexOf(callback);
if (index !== -1) {
this.listeners.splice(index, 1);
}
};
}
/**
* 向基座发送通知
* @param notification 通知消息
*/
sendNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
if (!this.props?.setGlobalState) {
console.warn('[子应用通信] 无法发送通知,setGlobalState 方法不可用');
return;
}
// 获取当前通知列表(需要通过 props 或缓存获取)
// 这里简化处理,直接通过 state 添加
const newNotification: Notification = {
...notification,
id: Date.now().toString(),
timestamp: Date.now(),
from: notification.from || 'Vue子应用',
};
// 通过修改全局状态来添加通知
// 注意:这里需要基座的 communication manager 来处理通知添加逻辑
// 所以我们实际上是触发一个状态变化,让基座来处理
this.setGlobalState({
notifications: [newNotification] as any, // 基座会合并到现有通知列表
});
}
/**
* 设置全局状态(向基座发送数据)
* @param state 要更新的状态
*/
setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) {
this.props.setGlobalState(state);
console.log('[子应用通信] 全局状态已更新:', state);
} else {
console.warn('[子应用通信] setGlobalState 方法不可用');
}
}
}
// 导出单例
export const subAppCommunication = new SubAppCommunicationManager();
/**
* Vue 组合式 API - 使用全局状态
* @param callback 状态变化回调
*/
export function useGlobalState(
callback: (state: GlobalState, prev: GlobalState) => void,
) {
const unsubscribe = subAppCommunication.onStateChange(callback);
// 在组件卸载时自动取消订阅
onUnmounted(() => {
unsubscribe();
});
return unsubscribe;
}
/**
* 便捷方法:发送通知到基座
*/
export function notify(
type: Notification['type'],
title: string,
message: string,
) {
subAppCommunication.sendNotification({
type,
title,
message,
});
}
<script setup lang="ts">
// About 页面
</script>
<template>
<div class="about-view">
<div class="content-card">
<h1>📖 关于本应用</h1>
<section class="section">
<h2>技术栈</h2>
<ul class="tech-list">
<li><strong>Vue 3</strong> - 渐进式 JavaScript 框架</li>
<li><strong>TypeScript</strong> - 类型安全的 JavaScript 超集</li>
<li><strong>Vite</strong> - 新一代前端构建工具</li>
<li><strong>Vue Router</strong> - 官方路由管理器</li>
<li><strong>Pinia</strong> - 新一代状态管理库</li>
<li><strong>qiankun</strong> - 微前端框架</li>
</ul>
</section>
<section class="section">
<h2>功能特性</h2>
<ul class="feature-list">
<li>✅ 支持独立运行和基座集成</li>
<li>✅ 完整的 TypeScript 支持</li>
<li>✅ 自动导入 API 和组件</li>
<li>✅ 热模块替换 (HMR)</li>
<li>✅ 路由懒加载</li>
<li>✅ CSS 样式隔离</li>
</ul>
</section>
<section class="section">
<h2>快速开始</h2>
<div class="code-block">
<pre><code># 安装依赖
pnpm install
# 启动开发服务器
pnpm dev
# 构建生产版本
pnpm build</code></pre>
</div>
</section>
</div>
</div>
</template>
<style scoped>
.about-view {
max-width: 900px;
margin: 0 auto;
}
.content-card {
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 2rem;
font-size: 2rem;
}
.section {
margin-bottom: 2rem;
}
.section h2 {
margin: 0 0 1rem;
font-size: 1.5rem;
color: rgb(255 255 255 / 95%);
}
.tech-list,
.feature-list {
padding: 0;
margin: 0;
list-style: none;
}
.tech-list li,
.feature-list li {
padding: 0.5rem 0;
line-height: 1.6;
opacity: 0.9;
}
.code-block {
padding: 1.5rem;
overflow-x: auto;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.5rem;
}
.code-block pre {
margin: 0;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.6;
}
.code-block code {
color: #a8e6cf;
}
</style>
<script setup lang="ts">
import type { GlobalState } from '@/utils/communication';
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { notify, useGlobalState } from '@/utils/communication';
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
const route = useRoute();
const counter = ref(0);
const globalState = ref<GlobalState | null>(null);
const runMode = computed(() => {
return qiankunWindow.__POWERED_BY_QIANKUN__ ? '🔗 基座模式' : '🏠 独立模式';
});
const currentRoute = computed(() => route.fullPath);
const increment = () => {
counter.value++;
};
const decrement = () => {
counter.value--;
};
// 监听主应用传递的全局状态
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
useGlobalState((state, prev) => {
console.log('📥 接收到主应用数据:', state);
console.log('📝 之前的数据:', prev);
globalState.value = state;
});
}
// 发送测试通知到主应用
const sendTestNotification = () => {
notify(
'success',
'来自微应用的通知',
`这是一条测试通知,发送时间: ${new Date().toLocaleTimeString()}`,
);
};
</script>
<template>
<div class="home-view">
<div class="hero-section">
<h1 class="hero-title">🎉 欢迎使用 Vue3 微前端子应用AAA</h1>
<p class="hero-subtitle">基于 qiankun + Vue3 + Vite + TypeScript 构建</p>
</div>
<div class="cards-grid">
<div class="card">
<div class="card-icon">🚀</div>
<h3>快速启动</h3>
<p>使用 Vite 构建,开发体验极速</p>
</div>
<div class="card">
<div class="card-icon">🎯</div>
<h3>独立运行</h3>
<p>支持独立开发和集成运行两种模式</p>
</div>
<div class="card">
<div class="card-icon">🔧</div>
<h3>开箱即用</h3>
<p>集成路由、状态管理等常用功能</p>
</div>
<div class="card">
<div class="card-icon">💡</div>
<h3>TypeScript</h3>
<p>完整的类型支持,开发更安全</p>
</div>
<div class="card">
<div class="card-icon">💡</div>
<p>{{ globalState }}</p>
</div>
</div>
<div class="info-section">
<h2>运行环境信息</h2>
<div class="info-content">
<div class="info-item">
<span class="info-label">运行模式:</span>
<span class="info-value">{{ runMode }}</span>
</div>
<div class="info-item">
<span class="info-label">当前路由:</span>
<span class="info-value">{{ currentRoute }}</span>
</div>
<div class="info-item">
<span class="info-label">计数器:</span>
<span class="info-value">{{ counter }}</span>
<button @click="increment" class="btn-primary">+1</button>
<button @click="decrement" class="btn-secondary">-1</button>
</div>
</div>
</div>
<!-- 主应用数据展示 -->
<div v-if="qiankunWindow.__POWERED_BY_QIANKUN__" class="info-section">
<h2>📡 主应用传递的数据</h2>
<div class="info-content">
<!-- 用户信息 -->
<div v-if="globalState?.user" class="data-group">
<h3 class="data-group-title">👤 用户信息</h3>
<div class="info-item">
<span class="info-label">用户ID:</span>
<span class="info-value">{{ globalState.user.id }}</span>
</div>
<div class="info-item">
<span class="info-label">用户名:</span>
<span class="info-value">{{ globalState.user.name }}</span>
</div>
<div class="info-item">
<span class="info-label">角色:</span>
<span class="info-value">{{ globalState.user.role }}</span>
</div>
<div class="info-item">
<span class="info-label">权限:</span>
<span class="info-value">{{
globalState.user.permissions.join(', ')
}}</span>
</div>
</div>
<!-- 主题配置 -->
<div v-if="globalState?.theme" class="data-group">
<h3 class="data-group-title">🎨 主题配置</h3>
<div class="info-item">
<span class="info-label">主题模式:</span>
<span class="info-value">{{ globalState.theme.mode }}</span>
</div>
<div class="info-item">
<span class="info-label">主色调:</span>
<span class="info-value">
<span :style="{ color: globalState.theme.primaryColor }">
{{ globalState.theme.primaryColor }}
</span>
</span>
</div>
</div>
<!-- 配置信息 -->
<div v-if="globalState?.config" class="data-group">
<h3 class="data-group-title">⚙️ 配置信息</h3>
<div class="info-item">
<span class="info-label">API地址:</span>
<span class="info-value">{{ globalState.config.apiBaseUrl }}</span>
</div>
<div class="info-item">
<span class="info-label">超时时间:</span>
<span class="info-value">{{ globalState.config.timeout }}ms</span>
</div>
</div>
<!-- 通知消息 -->
<div
v-if="
globalState?.notifications && globalState.notifications.length > 0
"
class="data-group"
>
<h3 class="data-group-title">
📢 通知消息 ({{ globalState.notifications.length }})
</h3>
<div
v-for="notification in globalState.notifications.slice(0, 3)"
:key="notification.id"
class="notification-item"
>
<span class="notification-type" :class="[notification.type]">{{
notification.type
}}</span>
<span class="notification-title">{{ notification.title }}</span>
<span class="notification-from" v-if="notification.from">来自: {{ notification.from }}</span>
</div>
</div>
<!-- 无数据提示 -->
<div v-if="!globalState" class="no-data">
<p>⏳ 等待主应用数据...</p>
</div>
</div>
<!-- 操作按钮 -->
<div class="actions">
<button @click="sendTestNotification" class="btn-action">
📤 发送测试通知到主应用
</button>
</div>
</div>
</div>
</template>
<style scoped>
.home-view {
max-width: 1200px;
margin: 0 auto;
}
.hero-section {
padding: 3rem 0;
margin-bottom: 3rem;
text-align: center;
}
.hero-title {
margin-bottom: 1rem;
font-size: 2.5rem;
font-weight: 700;
}
.hero-subtitle {
font-size: 1.2rem;
opacity: 0.9;
}
.cards-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
margin-bottom: 3rem;
}
.card {
padding: 2rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
transition: all 0.3s ease;
}
.card:hover {
background: rgb(255 255 255 / 15%);
box-shadow: 0 10px 30px rgb(0 0 0 / 20%);
transform: translateY(-5px);
}
.card-icon {
margin-bottom: 1rem;
font-size: 3rem;
}
.card h3 {
margin: 0 0 0.5rem;
font-size: 1.3rem;
}
.card p {
margin: 0;
opacity: 0.8;
}
.info-section {
padding: 2rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
}
.info-section h2 {
margin: 0 0 1.5rem;
font-size: 1.5rem;
}
.info-content {
display: flex;
flex-direction: column;
gap: 1rem;
}
.info-item {
display: flex;
gap: 1rem;
align-items: center;
}
.info-label {
min-width: 100px;
font-weight: 600;
}
.info-value {
padding: 0.5rem 1rem;
font-family: monospace;
background: rgb(255 255 255 / 10%);
border-radius: 0.5rem;
}
.btn-primary,
.btn-secondary {
padding: 0.5rem 1rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.btn-primary {
color: white;
background: rgb(76 175 80 / 80%);
}
.btn-primary:hover {
background: rgb(76 175 80 / 100%);
}
.btn-secondary {
color: white;
background: rgb(244 67 54 / 80%);
}
.btn-secondary:hover {
background: rgb(244 67 54 / 100%);
}
.data-group {
padding: 1rem;
margin-bottom: 1.5rem;
background: rgb(255 255 255 / 5%);
border-left: 3px solid rgb(255 255 255 / 30%);
border-radius: 0.5rem;
}
.data-group:last-child {
margin-bottom: 0;
}
.data-group-title {
margin: 0 0 1rem;
font-size: 1.1rem;
font-weight: 600;
opacity: 0.9;
}
.notification-item {
display: flex;
gap: 0.75rem;
align-items: center;
padding: 0.75rem;
margin-bottom: 0.5rem;
background: rgb(255 255 255 / 5%);
border-radius: 0.375rem;
}
.notification-item:last-child {
margin-bottom: 0;
}
.notification-type {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
border-radius: 0.25rem;
}
.notification-type.success {
color: rgb(76 175 80);
background: rgb(76 175 80 / 20%);
}
.notification-type.warning {
color: rgb(255 152 0);
background: rgb(255 152 0 / 20%);
}
.notification-type.error {
color: rgb(244 67 54);
background: rgb(244 67 54 / 20%);
}
.notification-type.info {
color: rgb(33 150 243);
background: rgb(33 150 243 / 20%);
}
.notification-title {
flex: 1;
font-weight: 500;
}
.notification-from {
font-size: 0.875rem;
opacity: 0.7;
}
.no-data {
padding: 2rem;
text-align: center;
opacity: 0.7;
}
.no-data p {
margin: 0;
font-size: 1.1rem;
}
.actions {
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 1.5rem;
}
.btn-action {
padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 600;
color: white;
cursor: pointer;
background: rgb(33 150 243 / 80%);
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.btn-action:hover {
background: rgb(33 150 243 / 100%);
box-shadow: 0 5px 15px rgb(33 150 243 / 30%);
transform: translateY(-2px);
}
</style>
<script setup lang="ts">
import { reactive } from 'vue';
interface Settings {
darkMode: boolean;
language: string;
notifications: {
desktop: boolean;
email: boolean;
sms: boolean;
};
security: {
sessionTimeout: number;
twoFactor: boolean;
};
theme: string;
timezone: string;
}
const defaultSettings: Settings = {
theme: 'purple',
darkMode: false,
notifications: {
desktop: true,
email: true,
sms: false,
},
language: 'zh-CN',
timezone: 'Asia/Shanghai',
security: {
twoFactor: false,
sessionTimeout: 30,
},
};
const settings = reactive<Settings>({ ...defaultSettings });
const saveSettings = () => {
console.log('保存设置:', settings);
alert('设置已保存!');
};
const resetSettings = () => {
if (confirm('确定要重置为默认设置吗?')) {
Object.assign(settings, defaultSettings);
alert('已重置为默认设置!');
}
};
</script>
<template>
<div class="settings-view">
<div class="content-card">
<h1>⚙️ 系统设置</h1>
<div class="settings-grid">
<div class="setting-group">
<h2>🎨 主题设置</h2>
<div class="setting-item">
<label>主题色:</label>
<select v-model="settings.theme" class="select-input">
<option value="purple">紫色</option>
<option value="blue">蓝色</option>
<option value="green">绿色</option>
<option value="orange">橙色</option>
</select>
</div>
<div class="setting-item">
<label>暗黑模式:</label>
<input
type="checkbox"
v-model="settings.darkMode"
class="checkbox-input"
/>
</div>
</div>
<div class="setting-group">
<h2>🔔 通知设置</h2>
<div class="setting-item">
<label>桌面通知:</label>
<input
type="checkbox"
v-model="settings.notifications.desktop"
class="checkbox-input"
/>
</div>
<div class="setting-item">
<label>邮件通知:</label>
<input
type="checkbox"
v-model="settings.notifications.email"
class="checkbox-input"
/>
</div>
<div class="setting-item">
<label>短信通知:</label>
<input
type="checkbox"
v-model="settings.notifications.sms"
class="checkbox-input"
/>
</div>
</div>
<div class="setting-group">
<h2>🌐 语言设置</h2>
<div class="setting-item">
<label>界面语言:</label>
<select v-model="settings.language" class="select-input">
<option value="zh-CN">简体中文</option>
<option value="en-US">English</option>
<option value="ja-JP">日本語</option>
</select>
</div>
<div class="setting-item">
<label>时区:</label>
<select v-model="settings.timezone" class="select-input">
<option value="Asia/Shanghai">北京时间 (UTC+8)</option>
<option value="America/New_York">纽约时间 (UTC-5)</option>
<option value="Europe/London">伦敦时间 (UTC+0)</option>
</select>
</div>
</div>
<div class="setting-group">
<h2>🔒 安全设置</h2>
<div class="setting-item">
<label>双因素认证:</label>
<input
type="checkbox"
v-model="settings.security.twoFactor"
class="checkbox-input"
/>
</div>
<div class="setting-item">
<label>会话超时 (分钟):</label>
<input
type="number"
v-model="settings.security.sessionTimeout"
class="number-input"
min="5"
max="120"
/>
</div>
</div>
</div>
<div class="actions">
<button @click="saveSettings" class="btn-save">💾 保存设置</button>
<button @click="resetSettings" class="btn-reset">🔄 重置默认</button>
</div>
<div class="current-settings">
<h3>当前配置 (JSON)</h3>
<pre>{{ JSON.stringify(settings, null, 2) }}</pre>
</div>
</div>
</div>
</template>
<style scoped>
.settings-view {
max-width: 1200px;
margin: 0 auto;
}
.content-card {
padding: 2.5rem;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 1rem;
backdrop-filter: blur(10px);
}
.content-card h1 {
margin: 0 0 2rem;
font-size: 2rem;
}
.settings-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
margin-bottom: 2rem;
}
.setting-group {
padding: 1.5rem;
background: rgb(255 255 255 / 5%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.75rem;
}
.setting-group h2 {
margin: 0 0 1rem;
font-size: 1.2rem;
color: rgb(255 255 255 / 95%);
}
.setting-item {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
}
.setting-item label {
font-weight: 500;
}
.select-input,
.number-input {
padding: 0.5rem;
font-size: 0.9rem;
color: white;
background: rgb(255 255 255 / 10%);
border: 1px solid rgb(255 255 255 / 20%);
border-radius: 0.5rem;
}
.number-input {
width: 80px;
}
.checkbox-input {
width: 20px;
height: 20px;
cursor: pointer;
}
.actions {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
}
.btn-save,
.btn-reset {
padding: 0.75rem 2rem;
font-weight: 600;
cursor: pointer;
border: none;
border-radius: 0.5rem;
transition: all 0.3s ease;
}
.btn-save {
color: white;
background: rgb(76 175 80 / 80%);
}
.btn-save:hover {
background: rgb(76 175 80 / 100%);
transform: translateY(-2px);
}
.btn-reset {
color: white;
background: rgb(158 158 158 / 80%);
}
.btn-reset:hover {
background: rgb(158 158 158 / 100%);
transform: translateY(-2px);
}
.current-settings {
padding: 1.5rem;
background: rgb(0 0 0 / 30%);
border: 1px solid rgb(255 255 255 / 10%);
border-radius: 0.75rem;
}
.current-settings h3 {
margin: 0 0 1rem;
font-size: 1.1rem;
}
.current-settings pre {
margin: 0;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.6;
color: #a8e6cf;
}
</style>
{
"compilerOptions": {
"target": "ES2020",
"jsx": "preserve",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
/* Path Alias */
"baseUrl": ".",
"module": "ESNext",
/* Bundler mode */
"moduleResolution": "bundler",
"paths": {
"@/*": ["src/*"]
},
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
/* Linting */
"strict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"references": [{ "path": "./tsconfig.node.json" }],
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

VITE_APP_NAME=venus-base
VITE_APP_VERSION=1.0.0
VITE_PORT=8080
VITE_API_BASE_URL=http://localhost:3000/api
VITE_API_TIMEOUT=30000
VITE_SUBAPP_VUE_ENTRY=http://localhost:8081
VITE_SUBAPP_REACT_ENTRY=http://localhost:8082
VITE_BASE_URL=/
VITE_USE_MOCK=true
VITE_DEBUG=true
VITE_LOGIN_EXPIRE_TIME=7200000
VITE_WS_URL=ws://localhost:3000/ws
VITE_UPLOAD_URL=http://localhost:3000/api/upload
# 登录系统使用文档
## 📋 概述
本文档介绍了 SCRM 微前端基座的登录系统实现,包括登录页面、状态管理、权限控制等核心功能。
## 🚀 功能特性
### 1. 登录页面
- ✅ 现代化 UI 设计,支持响应式布局
- ✅ 用户名密码登录
- ✅ 验证码功能(可选)
- ✅ 记住我功能
- ✅ 密码显示/隐藏切换
- ✅ 错误提示
- ✅ 加载状态显示
### 2. 状态管理(Pinia)
- ✅ 用户状态管理(`useUserStore`)
- ✅ 权限管理(`usePermissionStore`)
- ✅ 应用全局状态管理(`useAppStore`)
### 3. 认证与授权
- ✅ Token 存储和管理
- ✅ 自动刷新用户信息
- ✅ 路由守卫
- ✅ 权限检查
- ✅ 角色检查
### 4. API 封装
- ✅ Axios 请求拦截器
- ✅ 响应拦截器
- ✅ 自动添加 Token
- ✅ 统一错误处理
- ✅ 401/403 自动跳转
## 📁 文件结构
```
src/
├── api/ # API 接口
│ ├── index.ts # API 统一导出
│ └── user.ts # 用户相关 API
├── stores/ # Pinia 状态管理
│ ├── index.ts # Store 统一导出
│ ├── user.ts # 用户状态
│ ├── permission.ts # 权限状态
│ └── app.ts # 应用状态
├── utils/ # 工具函数
│ ├── index.ts # 工具统一导出
│ ├── auth.ts # 认证工具
│ ├── storage.ts # 存储工具
│ └── request.ts # 请求封装
├── types/ # 类型定义
│ ├── user.ts # 用户类型
│ └── api.ts # API 类型
├── views/ # 页面组件
│ └── Login.vue # 登录页面
└── router/ # 路由配置
└── index.ts # 路由守卫
```
## 🔐 登录流程
### 1. 用户登录流程
```mermaid
sequenceDiagram
participant U as 用户
participant L as Login.vue
participant S as UserStore
participant A as API
participant R as Router
U->>L: 输入用户名密码
U->>L: 点击登录
L->>S: 调用 login()
S->>A: POST /auth/login
A-->>S: 返回 token + userInfo
S->>S: 保存 token 和用户信息
S-->>L: 登录成功
L->>R: 跳转到首页
```
### 2. 路由守卫流程
```mermaid
graph TD
A[访问路由] --> B{有 Token?}
B -->|否| C{需要认证?}
C -->|是| D[跳转登录页]
C -->|否| E[允许访问]
B -->|是| F{已有用户信息?}
F -->|否| G[获取用户信息]
G --> H{获取成功?}
H -->|是| I{检查权限}
H -->|否| D
F -->|是| I
I -->|通过| E
I -->|不通过| J[跳转首页/403]
```
## 💻 使用示例
### 1. 登录
```vue
<script setup lang="ts">
import { useUserStore } from '@/stores';
const userStore = useUserStore();
const handleLogin = async () => {
const result = await userStore.login({
username: 'admin',
password: '123456',
});
if (result.success) {
console.log('登录成功');
}
};
</script>
```
### 2. 获取用户信息
```vue
<script setup lang="ts">
import { useUserStore } from '@/stores';
const userStore = useUserStore();
// 获取用户信息
console.log(userStore.userName);
console.log(userStore.userAvatar);
console.log(userStore.isLoggedIn);
</script>
```
### 3. 权限检查
```vue
<script setup lang="ts">
import { useUserStore } from '@/stores';
const userStore = useUserStore();
// 检查权限
if (userStore.hasPermission('user:create')) {
console.log('有创建用户权限');
}
// 检查角色
if (userStore.hasRole('admin')) {
console.log('是管理员');
}
</script>
```
### 4. 登出
```vue
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores';
const router = useRouter();
const userStore = useUserStore();
const handleLogout = async () => {
await userStore.logout();
router.push('/login');
};
</script>
```
### 5. 路由权限配置
```typescript
// router/index.ts
{
path: '/admin',
name: 'Admin',
component: () => import('@/views/Admin.vue'),
meta: {
title: '管理后台',
requiresAuth: true, // 需要登录
roles: ['admin'], // 需要 admin 角色
permissions: ['admin:view'], // 需要 admin:view 权限
},
}
```
## 🔧 配置
### 1. API 基础路径
在 `.env.development` 或 `.env.production` 中配置:
```env
# API 基础路径
VITE_API_BASE_URL=http://localhost:3000/api
```
### 2. 路由白名单
在 `router/index.ts` 中配置不需要登录的路由:
```typescript
const whiteList = ['/login', '/register', '/forgot-password'];
```
### 3. Token 存储 Key
在 `utils/auth.ts` 中配置:
```typescript
const TOKEN_KEY = 'scrm_access_token';
const REFRESH_TOKEN_KEY = 'scrm_refresh_token';
```
## 🌐 API 接口规范
### 1. 登录接口
**请求:**
```http
POST /auth/login
Content-Type: application/json
{
"username": "admin",
"password": "123456",
"captcha": "abcd" // 可选
}
```
**响应:**
```json
{
"code": 200,
"message": "登录成功",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "...",
"userInfo": {
"id": "1",
"username": "admin",
"name": "管理员",
"avatar": "https://...",
"roles": ["admin"],
"permissions": ["*:*:*"]
}
}
}
```
### 2. 获取用户信息接口
**请求:**
```http
GET /user/info
Authorization: Bearer {token}
```
**响应:**
```json
{
"code": 200,
"message": "success",
"data": {
"id": "1",
"username": "admin",
"name": "管理员",
"avatar": "https://...",
"roles": ["admin"],
"permissions": ["*:*:*"]
}
}
```
### 3. 登出接口
**请求:**
```http
POST /auth/logout
Authorization: Bearer {token}
```
**响应:**
```json
{
"code": 200,
"message": "登出成功"
}
```
## 🎨 样式定制
登录页面支持自定义样式,可以通过修改 `Login.vue` 中的 CSS 变量来调整:
```css
.login-container {
/* 背景渐变色 */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.login-button {
/* 按钮渐变色 */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
```
## 🔒 安全建议
1. **密码安全**
- 不在前端存储明文密码
- 使用 HTTPS 传输
- 密码输入框使用 autocomplete="current-password"
2. **Token 安全**
- Token 存储在 localStorage(建议生产环境使用 httpOnly cookie)
- 设置合理的过期时间
- 实现 Token 刷新机制
3. **权限控制**
- 前端权限检查 + 后端权限验证
- 敏感操作二次确认
- 最小权限原则
## 📝 测试
### 模拟后端 API
在实际后端接口未完成前,可以使用以下模拟数据:
```typescript
// 修改 api/user.ts 添加模拟数据
export const login = (data: LoginParams) => {
// 模拟登录
return Promise.resolve({
code: 200,
message: '登录成功',
data: {
token: 'mock_token_' + Date.now(),
userInfo: {
id: '1',
username: data.username,
name: '测试用户',
avatar: '👤',
roles: ['admin'],
permissions: ['*:*:*'],
},
},
});
};
```
## 🐛 常见问题
### 1. 刷新页面后需要重新登录?
检查是否正确从 localStorage 恢复 Token:
```typescript
// main.ts
const token = getToken();
if (token) {
userStore.setTokenValue(token);
}
```
### 2. 路由守卫死循环?
检查路由守卫中是否正确处理了白名单和登录页:
```typescript
if (to.path === '/login') {
next(); // 必须放行登录页
}
```
### 3. API 请求 401 错误?
检查请求拦截器是否正确添加 Token:
```typescript
config.headers['Authorization'] = `Bearer ${token}`;
```
## 📚 相关文档
- [Vue Router 文档](https://router.vuejs.org/)
- [Pinia 文档](https://pinia.vuejs.org/)
- [Axios 文档](https://axios-http.com/)
## 🙋 支持
如有问题,请联系开发团队或提交 Issue。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SCRM 微前端主应用</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
<script setup lang="ts">
// 根组件入口
</script>
<template>
<div id="main-app">
<router-view />
</div>
</template>
<style scoped>
#main-app {
width: 100%;
height: 100%;
min-height: 100vh;
}
</style>
/**
* GSC API 请求封装
*/
/**
* GSC POST 请求
*/
export function gscPost(url: string, data: any, _config: any = {}) {
console.log("BBBBBBB调用");
console.log(window.$gscApi, '========');
if (!window.$gscApi) {
throw new Error('$gscApi is not initialized. Please wait for the configuration to load.');
}
return window.$gscApi.post(url, data, _config);
}
import gscPost from '@/config/gscrequest';
// 数据看板指标统计
export function getdataBoard(data: any) {
console.log('SSSSS');
return gscPost('/dataBoard/index', data);
}
export const config = {
// 系统名字
sysName: "嘀加智享车生活",
// 系统说明
subName: "让你的生意慧简单",
// 是否需要注册-true;false
hasReg: false,
// 是否需要配置账号权限;true-有权限,从后台获取权限信息;false-无需权限
hasAuth: true,
subShopMerchantName: true, // 是否显示财务列表二级流量方
env: "production",
alipayPath: "https://dj.glsx.com.cn/dj-carlife-web-alipay/#/alipay",
css_url:
"https://oss-config.test.glsx.com.cn/mock/5be17454f31545347559d499/config/index.css",
axios: {
baseURL: "https://dj.glsx.com.cn/rop-dj-smartcarlife/router",
appkey: "d7ffc3346fc9a45bccaaa35300d59022",
secret: "4bc07f8868374c49a4661d603377e3106fc9a45bccaaa353",
timeout: 50000,
result: {
data_key: "data",
message_key: "message",
code_key: "code",
code_success_value: 0,
code_message_map: {}
}
},
axios2: {
baseURL: "https://scrm.glsx.com.cn/rop-scrm-shopmall/router",
appkey: "48e5e13229b82c1b4e6e8c96151f0637",
secret: "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b",
timeout: 50000,
result: {
data_key: "data",
message_key: "message",
code_key: "code",
code_success_value: 0,
code_message_map: {}
}
},
common: {
baseURL:
"http://didicb.glsx.com.cn/router?method=glsx.accounts.biz.common.pictureUpload",
appkey: "48e5e13229b82c1b4e6e8c96151f0637",
secret: "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b",
timeout: 50000,
result: {
data_key: "data",
message_key: "message",
code_key: "code",
code_success_value: 0,
code_message_map: {}
}
}
}
<script setup lang="ts">
import type { MenuItem } from '@/types/menu';
import { computed } from 'vue';
import SidebarMenuItem from './SidebarMenuItem.vue';
interface Props {
menu: MenuItem;
activePath: string;
expandedKeys: Set<string>;
}
const props = defineProps<Props>();
const emit = defineEmits<{
click: [menu: MenuItem];
toggle: [menuId: string];
}>();
// 是否有子菜单
const hasChildren = computed(() => {
return props.menu.children && props.menu.children.length > 0;
});
// 是否展开
const isExpanded = computed(() => {
return props.expandedKeys.has(props.menu.id);
});
// 是否激活(当前路由或子路由激活)
const isActive = computed(() => {
return (
props.activePath === props.menu.path ||
props.activePath.startsWith(`${props.menu.path}/`)
);
});
// 点击菜单项
const handleClick = () => {
if (hasChildren.value) {
handleToggle();
} else {
emit('click', props.menu);
}
};
// 展开/收起子菜单
const handleToggle = () => {
emit('toggle', props.menu.id);
};
</script>
<template>
<div class="sidebar-menu-item">
<!-- 菜单项本身 -->
<div
class="menu-item-content"
:class="{
active: isActive,
'has-children': hasChildren,
[`level-${menu.level || 1}`]: true,
}"
@click="handleClick"
>
<!-- 展开/收起图标 -->
<span v-if="hasChildren" class="expand-icon" @click.stop="handleToggle">
{{ isExpanded ? '▼' : '▶' }}
</span>
<!-- 菜单图标 -->
<span v-if="menu.icon" class="menu-icon">{{ menu.icon }}</span>
<!-- 菜单标题 -->
<span class="menu-title">{{ menu.title }}</span>
<!-- 徽章 -->
<span v-if="menu.meta?.badge" class="menu-badge">
{{ menu.meta.badge }}
</span>
</div>
<!-- 子菜单 -->
<transition name="submenu-expand">
<div v-if="hasChildren && isExpanded" class="submenu">
<SidebarMenuItem
v-for="child in menu.children"
:key="child.id"
:menu="child"
:active-path="activePath"
:expanded-keys="expandedKeys"
@click="$emit('click', $event)"
@toggle="$emit('toggle', $event)"
/>
</div>
</transition>
</div>
</template>
<style scoped>
.sidebar-menu-item {
width: 100%;
}
.menu-item-content {
position: relative;
display: flex;
gap: 8px;
align-items: center;
padding: 10px 16px;
color: #333;
cursor: pointer;
user-select: none;
transition: all 0.3s;
}
/* 层级缩进 */
.menu-item-content.level-1 {
padding-left: 16px;
}
.menu-item-content.level-2 {
padding-left: 32px;
font-size: 13px;
}
.menu-item-content.level-3 {
padding-left: 48px;
font-size: 12px;
}
.menu-item-content:hover {
color: #1890ff;
background-color: #f5f5f5;
}
.menu-item-content.active {
font-weight: 500;
color: #1890ff;
background-color: #e6f7ff;
}
.menu-item-content.active::before {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 3px;
content: '';
background-color: #1890ff;
}
.expand-icon {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
font-size: 10px;
color: #666;
transition: transform 0.3s;
}
.menu-icon {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
font-size: 16px;
}
.menu-title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.menu-badge {
flex-shrink: 0;
min-width: 18px;
height: 18px;
padding: 0 6px;
font-size: 11px;
line-height: 18px;
color: #fff;
text-align: center;
background-color: #ff4d4f;
border-radius: 9px;
}
.submenu {
overflow: hidden;
}
/* 子菜单展开动画 */
.submenu-expand-enter-active,
.submenu-expand-leave-active {
transition: all 0.3s ease;
}
.submenu-expand-enter-from,
.submenu-expand-leave-to {
max-height: 0;
opacity: 0;
transform: translateY(-10px);
}
.submenu-expand-enter-to,
.submenu-expand-leave-from {
max-height: 1000px;
opacity: 1;
transform: translateY(0);
}
/* 有子菜单的项目样式 */
.menu-item-content.has-children {
font-weight: 500;
}
/* 二级菜单样式 */
.level-2 .menu-item-content {
background-color: rgb(0 0 0 / 2%);
}
.level-2 .menu-item-content:hover {
background-color: #f0f0f0;
}
/* 三级菜单样式 */
.level-3 .menu-item-content {
background-color: rgb(0 0 0 / 4%);
}
.level-3 .menu-item-content:hover {
background-color: #ebebeb;
}
</style>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores';
const router = useRouter();
const userStore = useUserStore();
// 下拉菜单显示状态
const showDropdown = ref(false);
// 确认对话框显示状态
const showConfirmDialog = ref(false);
// 角色文本映射
const getRoleText = () => {
const roles = userStore.roles;
if (!roles || roles.length === 0) return '普通用户';
const roleMap: Record<string, string> = {
admin: '管理员',
user: '普通用户',
guest: '访客',
developer: '开发者',
manager: '经理',
};
return roleMap[roles[0]] || roles[0];
};
// 切换下拉菜单
const toggleDropdown = () => {
showDropdown.value = !showDropdown.value;
};
// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (!target.closest('.user-card')) {
showDropdown.value = false;
}
};
// 个人中心
const handleProfile = () => {
showDropdown.value = false;
// 这里可以跳转到个人中心页面
// router.push('/profile');
};
// 设置
const handleSettings = () => {
showDropdown.value = false;
// 这里可以跳转到设置页面
// router.push('/settings');
};
// 处理退出登录
const handleLogout = () => {
showDropdown.value = false;
showConfirmDialog.value = true;
};
// 确认退出登录
const confirmLogout = async () => {
try {
// 关闭对话框
showConfirmDialog.value = false;
// 调用退出登录
await userStore.logout();
// 跳转到登录页
router.push('/login');
} catch {
// 即使失败也跳转到登录页
router.push('/login');
}
};
// 组件挂载
onMounted(() => {
// 监听点击外部事件
document.addEventListener('click', handleClickOutside);
});
// 组件卸载
onUnmounted(() => {
// 移除监听
document.removeEventListener('click', handleClickOutside);
});
</script>
<template>
<div class="user-info">
<!-- 已登录状态 -->
<div v-if="userStore.isLoggedIn" class="user-card" @click="toggleDropdown">
<div class="user-avatar">{{ userStore.userAvatar || '👤' }}</div>
<div class="user-details">
<div class="user-name">{{ userStore.userName }}</div>
<div class="user-role">{{ getRoleText() }}</div>
</div>
<div class="dropdown-icon">▼</div>
<!-- 下拉菜单 -->
<div v-if="showDropdown" class="user-dropdown" @click.stop>
<div class="dropdown-header">
<div class="dropdown-avatar">{{ userStore.userAvatar || '👤' }}</div>
<div class="dropdown-info">
<div class="dropdown-name">{{ userStore.userName }}</div>
<div class="dropdown-id">ID: {{ userStore.userId }}</div>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="dropdown-menu">
<div class="menu-item" @click="handleProfile">
<span class="menu-icon">👤</span>
<span>个人中心</span>
</div>
<div class="menu-item" @click="handleSettings">
<span class="menu-icon">⚙️</span>
<span>设置</span>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="dropdown-footer">
<button class="logout-btn" @click="handleLogout">
<span class="logout-icon">🚪</span>
<span>退出登录</span>
</button>
</div>
</div>
</div>
<!-- 未登录状态 -->
<div v-else class="user-empty">
<router-link to="/login" class="login-link">登录</router-link>
</div>
<!-- 确认对话框 -->
<div
v-if="showConfirmDialog"
class="confirm-dialog-overlay"
@click="showConfirmDialog = false"
>
<div class="confirm-dialog" @click.stop>
<div class="dialog-header">
<span class="dialog-icon">❓</span>
<h3 class="dialog-title">确认退出</h3>
</div>
<div class="dialog-content">
<p>确定要退出登录吗?</p>
</div>
<div class="dialog-footer">
<button
class="dialog-btn cancel-btn"
@click="showConfirmDialog = false"
>
取消
</button>
<button class="dialog-btn confirm-btn" @click="confirmLogout">
确认退出
</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
@keyframes dropdown-slide-in {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes dialog-slide-in {
from {
opacity: 0;
transform: scale(0.9);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* 响应式 */
@media (max-width: 768px) {
.user-dropdown {
min-width: 260px;
}
.confirm-dialog {
width: 95%;
}
}
.user-info {
position: relative;
padding: 8px;
}
/* 用户卡片 */
.user-card {
position: relative;
display: flex;
gap: 12px;
align-items: center;
padding: 12px;
cursor: pointer;
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgb(0 0 0 / 8%);
transition: all 0.3s;
}
.user-card:hover {
box-shadow: 0 4px 12px rgb(0 0 0 / 12%);
transform: translateY(-1px);
}
.user-avatar {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
font-size: 28px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 50%;
}
.user-details {
flex: 1;
min-width: 0;
}
.user-name {
margin-bottom: 4px;
overflow: hidden;
text-overflow: ellipsis;
font-size: 16px;
font-weight: 600;
color: #262626;
white-space: nowrap;
}
.user-role {
font-size: 14px;
color: #8c8c8c;
}
.dropdown-icon {
flex-shrink: 0;
font-size: 10px;
color: #8c8c8c;
transition: transform 0.3s;
}
.user-card:hover .dropdown-icon {
color: #667eea;
}
/* 下拉菜单 */
.user-dropdown {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 1000;
min-width: 280px;
background: white;
border-radius: 8px;
box-shadow: 0 8px 24px rgb(0 0 0 / 15%);
animation: dropdown-slide-in 0.2s ease-out;
}
.dropdown-header {
display: flex;
gap: 12px;
align-items: center;
padding: 16px;
}
.dropdown-avatar {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
font-size: 32px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 50%;
}
.dropdown-info {
flex: 1;
min-width: 0;
}
.dropdown-name {
margin-bottom: 4px;
overflow: hidden;
text-overflow: ellipsis;
font-size: 18px;
font-weight: 600;
color: #262626;
white-space: nowrap;
}
.dropdown-id {
font-size: 13px;
color: #8c8c8c;
}
.dropdown-divider {
height: 1px;
margin: 0 8px;
background: #f0f0f0;
}
.dropdown-menu {
padding: 8px;
}
.menu-item {
display: flex;
gap: 12px;
align-items: center;
padding: 12px 16px;
font-size: 14px;
color: #262626;
cursor: pointer;
border-radius: 6px;
transition: all 0.2s;
}
.menu-item:hover {
color: #667eea;
background: #f5f5f5;
}
.menu-icon {
font-size: 18px;
}
.dropdown-footer {
padding: 8px;
}
.logout-btn {
display: flex;
gap: 8px;
align-items: center;
justify-content: center;
width: 100%;
padding: 12px 16px;
font-size: 14px;
font-weight: 500;
color: white;
cursor: pointer;
background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
border: none;
border-radius: 6px;
transition: all 0.3s;
}
.logout-btn:hover {
box-shadow: 0 4px 12px rgb(255 77 79 / 30%);
transform: translateY(-2px);
}
.logout-btn:active {
transform: translateY(0);
}
.logout-icon {
font-size: 16px;
}
/* 未登录状态 */
.user-empty {
padding: 12px;
text-align: center;
}
.login-link {
display: inline-block;
padding: 8px 24px;
font-size: 14px;
font-weight: 500;
color: white;
text-decoration: none;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 6px;
transition: all 0.3s;
}
.login-link:hover {
box-shadow: 0 4px 12px rgb(102 126 234 / 30%);
transform: translateY(-2px);
}
/* 确认对话框 */
.confirm-dialog-overlay {
position: fixed;
inset: 0;
z-index: 2000;
display: flex;
align-items: center;
justify-content: center;
background: rgb(0 0 0 / 50%);
animation: fade-in 0.2s ease-out;
}
.confirm-dialog {
width: 90%;
max-width: 400px;
background: white;
border-radius: 12px;
box-shadow: 0 12px 40px rgb(0 0 0 / 20%);
animation: dialog-slide-in 0.3s ease-out;
}
.dialog-header {
display: flex;
gap: 12px;
align-items: center;
padding: 24px 24px 16px;
}
.dialog-icon {
font-size: 32px;
}
.dialog-title {
margin: 0;
font-size: 20px;
font-weight: 600;
color: #262626;
}
.dialog-content {
padding: 0 24px 24px;
}
.dialog-content p {
margin: 0;
font-size: 15px;
line-height: 1.6;
color: #595959;
}
.dialog-footer {
display: flex;
gap: 12px;
padding: 16px 24px;
border-top: 1px solid #f0f0f0;
}
.dialog-btn {
flex: 1;
padding: 12px 24px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
border: none;
border-radius: 6px;
transition: all 0.3s;
}
.cancel-btn {
color: #595959;
background: #f5f5f5;
}
.cancel-btn:hover {
background: #e8e8e8;
}
.confirm-btn {
color: white;
background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
}
.confirm-btn:hover {
box-shadow: 0 4px 12px rgb(255 77 79 / 30%);
transform: translateY(-2px);
}
.confirm-btn:active,
.cancel-btn:active {
transform: translateY(0);
}
</style>
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!