Commit fc688d3d by liimin

docs(repo): 添加协作约定并更新质量检查配置

- 新增 AGENTS.md 文件定义仓库协作约定和工作规则
- 添加防御性检查工作流 defense.yml 包含 lint/type/contract 等检查
- 更新 prettierignore 和 stylelintignore 配置忽略特定目录
- 在 package.json 中新增多个质量检查脚本命令
- 配置 lefthook pre-push 钩子执行智能检查
- 更新 eslint 配置忽略 uniappX 目录的存量问题
- 优化多个 uniappX 项目的代码格式和配置文件
- 调整 github actions codeql 工作流配置简化语言检测
1 parent 058d6dae
Showing 118 changed files with 2252 additions and 904 deletions
# 对于大多数项目而言,此工作流文件无需修改,你只需将其提交至代码仓库即可。 # 使用 GitHub CodeQL 对代码进行静态安全分析。
# 你也可以根据需要修改此文件,以此覆盖默认的待分析语言集合,或配置自定义查询语句、构建逻辑。 # 当前仓库以 JavaScript / TypeScript 为主,因此只启用 `javascript-typescript`。
# ******** 注意事项 ********
# 我们已尝试自动检测你代码仓库中的开发语言。请务必检查下方定义的 language 矩阵,确认其包含的 CodeQL 支持语言集准确无误。
# 使用 GitHub CodeQL 对代码进行静态安全分析,检测潜在的代码漏洞和安全问题。 name: CodeQL
name: "CodeQL"
# 触发条件:
# 推送到 main 分支
# PR 到 main 分支
# 每周日午夜定时运行(0 35 * * 0)
on: on:
push: push:
branches: ["main"] branches: ["main"]
...@@ -23,23 +15,11 @@ jobs: ...@@ -23,23 +15,11 @@ jobs:
analyze: analyze:
name: Analyze (${{ matrix.language }}) name: Analyze (${{ matrix.language }})
if: github.repository == 'monorepo/venus' if: github.repository == 'monorepo/venus'
# Runner size impacts CodeQL analysis time. To learn more, please see: runs-on: ubuntu-latest
# - https://gh.io/recommended-hardware-resources-for-running-codeql timeout-minutes: 360
# - 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: permissions:
# required for all workflows
security-events: write security-events: write
# required to fetch internal or private CodeQL packs
packages: read packages: read
# only required for workflows in private repositories
actions: read actions: read
contents: read contents: read
strategy: strategy:
...@@ -48,48 +28,23 @@ jobs: ...@@ -48,48 +28,23 @@ jobs:
include: include:
- language: javascript-typescript - language: javascript-typescript
build-mode: none 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: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v3 uses: github/codeql-action/init@v3
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }} 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' - if: matrix.build-mode == 'manual'
shell: bash shell: bash
run: | run: |
echo 'If you are using a "manual" build mode for one or more of the' \ echo '当前语言被设置为 manual build-mode,请在这里补充项目构建命令。'
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1 exit 1
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3 uses: github/codeql-action/analyze@v3
with: with:
category: "/language:${{matrix.language}}" category: "/language:${{ matrix.language }}"
name: defense
on:
pull_request:
push:
branches:
- main
- master
- dev
jobs:
quality:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10.14.0
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- name: Install
run: pnpm install --frozen-lockfile
- name: Lint
run: pnpm lint
- name: Typecheck
run: pnpm run check:type
- name: Template Contract
run: pnpm run check:template-contract
- name: Review Trigger
run: pnpm run review:trigger
- name: Fitness Fast
run: pnpm run check:fitness -- --tier fast
...@@ -8,6 +8,13 @@ coverage ...@@ -8,6 +8,13 @@ coverage
CODEOWNERS CODEOWNERS
.nitro .nitro
.output .output
.comate
.lingma
.vscode
**/.hbuilderx
**/uni_modules
**/unpackage
**/devTools
**/*.uvue **/*.uvue
**/*.uts **/*.uts
**/*.vue **/*.vue
...@@ -33,4 +40,3 @@ unpackage ...@@ -33,4 +40,3 @@ unpackage
!*.wxml !*.wxml
!*.json !*.json
...@@ -5,3 +5,4 @@ coverage ...@@ -5,3 +5,4 @@ coverage
miniprogram_npm miniprogram_npm
uni_modules uni_modules
wxcomponents wxcomponents
apps/uniappX/**
# Venus Agent 协作约定
## 使命
- 在共享的 `venus` monorepo 中以小步、可回退的方式工作。
- 把仓库视为一个受治理的工程系统,而不是自由发挥的试验场。
- 涉及模板、共享包和工作区工具链时,优先采用 contract-first 的修改方式。
## 阅读顺序
1. 先阅读本文件。
2. 涉及架构判断时,阅读 `docs/architecture/ARCHITECTURE.md`。
3. 涉及执行计划时,阅读 `docs/exec-plans/README.md`。
4. 涉及 AI 失败反馈时,阅读 `docs/issues/ai-failures/README.md`。
5. 涉及质量门禁时,阅读 `docs/fitness/README.md` 及其引用的维度文档。
6. 修改 `packages/cli/templates/**` 前,先阅读 `contracts/templates/*.contract.json`。
## 仓库地图
- `apps/`:生成后的应用与业务代码。
- `packages/cli/`:Venus CLI 及模板交付链路。
- `packages/cli/templates/`:脚手架模板与可选能力。
- `internal/`:共享 lint、tsconfig 与构建策略包。
- `scripts/`:共享自动化入口。
- `contracts/`:可被机器校验的仓库契约。
- `tools/fitness/`:质量执行引擎。
- `docs/`:架构、计划、失败记录与治理证据。
## 工作规则
- 让改动保持在最小但有意义的范围内。
- 如果修改了模板能力,必须在同一次变更中同步更新对应的 contract 和校验逻辑。
- 如果修改了高风险路径,必须补充或更新 `docs/exec-plans/`、`docs/fitness/` 或 `docs/issues/ai-failures/` 中的证据。
- 不要静默修改根级工作区配置行为。
- 优先做增量、可审查的修改,而不是大范围重构。
## 高风险路径
- `packages/cli/**`
- `packages/cli/templates/**`
- `internal/lint-configs/**`
- `internal/tsconfig/**`
- `scripts/build/**`
- `contracts/**`
- 根 `package.json`
- `pnpm-workspace.yaml`
- `lefthook.yml`
- `.github/workflows/**`
## 必备证据
- 模板能力变更:需要 contract 更新和校验结果。
- 共享配置变更:需要执行计划或失败记录中的原因说明。
- 治理脚本变更:需要 fitness 或 smart-check 的验证证据。
## 验证顺序
1. `pnpm lint`
2. `pnpm run check:type`
3. `pnpm run check:template-contract`
4. `pnpm run review:trigger`
5. `pnpm run check:file-budget`
6. `pnpm run check:fitness -- --tier fast`
## 失败处理
- 如果一次改动暴露出缺失的防护规则,要记录到 `docs/issues/ai-failures/`。
- 对于重复出现的失败,要把它沉淀为 contract、hook、脚本或 fitness 规则。
- 不要依赖记忆避免同类问题,能写成仓库规则的就写成仓库规则。
#### 项目介绍 #### 项目介绍
萤火商城V2.0,是2021年全新推出的一款轻量级、高性能、前后端分离的电商系统,支持微信小程序 + H5+ 公众号 + APP,前后端源码完全开源,看见及所得,完美支持二次开发,可学习可商用,让您快速搭建个性化独立商城。 萤火商城V2.0,是2021年全新推出的一款轻量级、高性能、前后端分离的电商系统,支持微信小程序 + H5+ 公众号 + APP,前后端源码完全开源,看见及所得,完美支持二次开发,可学习可商用,让您快速搭建个性化独立商城。
如果对您有帮助,您可以点右上角 “Star” 收藏一下 ,获取第一时间更新,谢谢! 如果对您有帮助,您可以点右上角 “Star” 收藏一下 ,获取第一时间更新,谢谢!
...@@ -31,15 +32,13 @@ ...@@ -31,15 +32,13 @@
5. 打开微信开发者工具 导入 打包完成的项目 5. 打开微信开发者工具 导入 打包完成的项目
6. 检查没有运行错误,在右上方上传小程序 6. 检查没有运行错误,在右上方上传小程序
#### UNIAPP-页面展示 #### UNIAPP-页面展示
![前端展示](https://images.gitee.com/uploads/images/2021/0316/215102_7bcb0802_2166072.png "前端展示.png") ![前端展示](https://images.gitee.com/uploads/images/2021/0316/215102_7bcb0802_2166072.png "前端展示.png")
#### 系统演示 #### 系统演示
![前端演示二维码](https://images.gitee.com/uploads/images/2021/0316/104516_3778337e_2166072.png "111.png")
![前端演示二维码](https://images.gitee.com/uploads/images/2021/0316/104516_3778337e_2166072.png "111.png")
#### 版权须知 #### 版权须知
......
<!DOCTYPE html> <!doctype html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="shortcut icon" href="static/logo.png" type="image/x-icon" /> <link rel="shortcut icon" href="static/logo.png" type="image/x-icon" />
<script> <script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || var coverSupport =
CSS.supports('top: constant(a)')) "CSS" in window &&
typeof CSS.supports === "function" &&
(CSS.supports("top: env(a)") || CSS.supports("top: constant(a)"));
document.write( document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />') (coverSupport ? ", viewport-fit=cover" : "") +
'" />',
);
</script> </script>
<title></title> <title></title>
<!--preload-links--> <!--preload-links-->
......
{ {
"pages": [{ "pages": [
{
"path": "pages/index/index", "path": "pages/index/index",
"style": { "style": {
"navigationStyle": "custom" "navigationStyle": "custom"
...@@ -31,9 +32,11 @@ ...@@ -31,9 +32,11 @@
} }
} }
], ],
"subPackages": [{ "subPackages": [
{
"root": "pages/subHome", "root": "pages/subHome",
"pages": [{ "pages": [
{
"path": "search", "path": "search",
"style": { "style": {
"navigationBarTitleText": "搜索", "navigationBarTitleText": "搜索",
...@@ -58,7 +61,8 @@ ...@@ -58,7 +61,8 @@
}, },
{ {
"root": "pages/login", "root": "pages/login",
"pages": [{ "pages": [
{
"path": "login", "path": "login",
"style": { "style": {
"navigationBarTitleText": "登录", "navigationBarTitleText": "登录",
...@@ -83,7 +87,8 @@ ...@@ -83,7 +87,8 @@
}, },
{ {
"root": "pages/subMoments", "root": "pages/subMoments",
"pages": [{ "pages": [
{
"path": "release-moment", "path": "release-moment",
"style": { "style": {
"navigationBarTitleText": "发布动态", "navigationBarTitleText": "发布动态",
...@@ -108,7 +113,8 @@ ...@@ -108,7 +113,8 @@
}, },
{ {
"root": "pages/subMine", "root": "pages/subMine",
"pages": [{ "pages": [
{
"path": "settings", "path": "settings",
"style": { "style": {
"navigationBarTitleText": "设置", "navigationBarTitleText": "设置",
...@@ -147,7 +153,8 @@ ...@@ -147,7 +153,8 @@
}, },
{ {
"root": "pages/order", "root": "pages/order",
"pages": [{ "pages": [
{
"path": "submit-order-page", "path": "submit-order-page",
"style": { "style": {
"navigationBarTitleText": "提交订单", "navigationBarTitleText": "提交订单",
...@@ -211,7 +218,8 @@ ...@@ -211,7 +218,8 @@
"selectedColor": "#00b96b", "selectedColor": "#00b96b",
"backgroundColor": "#fff", "backgroundColor": "#fff",
"borderStyle": "white", "borderStyle": "white",
"list": [{ "list": [
{
"text": "首页", "text": "首页",
"pagePath": "pages/index/index", "pagePath": "pages/index/index",
"iconPath": "/static/images/tabbar/home.png", "iconPath": "/static/images/tabbar/home.png",
......
// 参考链接 https://doc.dcloud.net.cn/uni-app-x/tutorial/ls-plugin.html#setting // 参考链接 https://doc.dcloud.net.cn/uni-app-x/tutorial/ls-plugin.html#setting
{ {
"targets": [ "targets": ["APP-ANDROID"]
"APP-ANDROID"
]
} }
...@@ -19,14 +19,6 @@ ...@@ -19,14 +19,6 @@
"vueCompilerOptions": { "vueCompilerOptions": {
"extensions": [".vue", ".uvue"] "extensions": [".vue", ".uvue"]
}, },
"include": [ "include": ["**/*.uts", "**/*.ts", "main.ts", "**/*.uvue", "**/*.vue", "App.uvue", "**/*.d.ts"],
"**/*.uts",
"**/*.ts",
"main.ts",
"**/*.uvue",
"**/*.vue",
"App.uvue",
"**/*.d.ts"
],
"exclude": ["node_modules", "dist", "unpackage"] "exclude": ["node_modules", "dist", "unpackage"]
} }
...@@ -21,32 +21,32 @@ $uni-color-warning: #f0ad4e; ...@@ -21,32 +21,32 @@ $uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d; $uni-color-error: #dd524d;
/* 文字基本颜色 */ /* 文字基本颜色 */
$uni-text-color:#333;//基本色 $uni-text-color: #333; //基本色
$uni-text-color-inverse:#fff;//反色 $uni-text-color-inverse: #fff; //反色
$uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息 $uni-text-color-grey: #999; //辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080; $uni-text-color-placeholder: #808080;
$uni-text-color-disable:#c0c0c0; $uni-text-color-disable: #c0c0c0;
/* 背景颜色 */ /* 背景颜色 */
$uni-bg-color:#fff; $uni-bg-color: #fff;
$uni-bg-color-grey:#f8f8f8; $uni-bg-color-grey: #f8f8f8;
$uni-bg-color-hover:#f1f1f1;//点击状态颜色 $uni-bg-color-hover: #f1f1f1; //点击状态颜色
$uni-bg-color-mask:rgb(0 0 0 / 40%);//遮罩颜色 $uni-bg-color-mask: rgb(0 0 0 / 40%); //遮罩颜色
/* 边框颜色 */ /* 边框颜色 */
$uni-border-color:#c8c7cc; $uni-border-color: #c8c7cc;
/* 尺寸变量 */ /* 尺寸变量 */
/* 文字尺寸 */ /* 文字尺寸 */
$uni-font-size-sm:12px; $uni-font-size-sm: 12px;
$uni-font-size-base:14px; $uni-font-size-base: 14px;
$uni-font-size-lg:16px; $uni-font-size-lg: 16px;
/* 图片尺寸 */ /* 图片尺寸 */
$uni-img-size-sm:20px; $uni-img-size-sm: 20px;
$uni-img-size-base:26px; $uni-img-size-base: 26px;
$uni-img-size-lg:40px; $uni-img-size-lg: 40px;
/* Border Radius */ /* Border Radius */
$uni-border-radius-sm: 2px; $uni-border-radius-sm: 2px;
...@@ -68,9 +68,9 @@ $uni-spacing-col-lg: 12px; ...@@ -68,9 +68,9 @@ $uni-spacing-col-lg: 12px;
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度 $uni-opacity-disabled: 0.3; // 组件禁用态的透明度
/* 文章场景相关 */ /* 文章场景相关 */
$uni-color-title: #2C405A; // 文章标题颜色 $uni-color-title: #2c405a; // 文章标题颜色
$uni-font-size-title:20px; $uni-font-size-title: 20px;
$uni-color-subtitle: #555; // 二级标题颜色 $uni-color-subtitle: #555; // 二级标题颜色
$uni-font-size-subtitle:26px; $uni-font-size-subtitle: 26px;
$uni-color-paragraph: #3F536E; // 文章段落颜色 $uni-color-paragraph: #3f536e; // 文章段落颜色
$uni-font-size-paragraph:15px; $uni-font-size-paragraph: 15px;
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
--l-radius-md: 8px; --l-radius-md: 8px;
--l-radius-lg: 12px; --l-radius-lg: 12px;
--l-radius-xl: 16px; --l-radius-xl: 16px;
--l-radius-a : 100rpx; --l-radius-a: 100rpx;
/* 接待中心左右模块宽度(1173x768 基准),LayoutService 动态覆盖 */ /* 接待中心左右模块宽度(1173x768 基准),LayoutService 动态覆盖 */
--l-reception-left-width: 328px; --l-reception-left-width: 328px;
--l-reception-right-width: 677px; --l-reception-right-width: 677px;
......
...@@ -5,12 +5,14 @@ ...@@ -5,12 +5,14 @@
HomeFrame 采用现代化的企业级设计语言,融合以下核心设计理念: HomeFrame 采用现代化的企业级设计语言,融合以下核心设计理念:
### 设计原则 ### 设计原则
- **视觉层次**:通过阴影、渐变、圆角建立清晰的层级关系 - **视觉层次**:通过阴影、渐变、圆角建立清晰的层级关系
- **微交互**:悬停效果、过渡动画提升用户体验 - **微交互**:悬停效果、过渡动画提升用户体验
- **响应式适配**:横竖屏自动切换,多分辨率精确适配 - **响应式适配**:横竖屏自动切换,多分辨率精确适配
- **一致性**:统一的设计令牌(Design Tokens)确保视觉一致性 - **一致性**:统一的设计令牌(Design Tokens)确保视觉一致性
### 核心特性 ### 核心特性
✨ **玻璃态卡片** - `backdrop-filter: blur(10px)` 营造现代感 ✨ **玻璃态卡片** - `backdrop-filter: blur(10px)` 营造现代感
🌈 **渐变色彩** - 企业级渐变色方案(primary/secondary/success) 🌈 **渐变色彩** - 企业级渐变色方案(primary/secondary/success)
💫 **流畅动画** - cubic-bezier 缓动函数实现自然过渡 💫 **流畅动画** - cubic-bezier 缓动函数实现自然过渡
...@@ -36,37 +38,37 @@ HomeFrame 组件采用 **CSS 变量 + layout-root** 的响应式方案,无需 ...@@ -36,37 +38,37 @@ HomeFrame 组件采用 **CSS 变量 + layout-root** 的响应式方案,无需
export default { export default {
common: { common: {
// 所有场景通用 // 所有场景通用
'--common-title-height': '48px', "--common-title-height": "48px",
// 设计系统变量 // 设计系统变量
'--l-spacing-sm': '8px', "--l-spacing-sm": "8px",
'--l-radius-lg': '16px', "--l-radius-lg": "16px",
'--l-shadow-md': '0 4px 16px rgba(0, 0, 0, 0.08)', "--l-shadow-md": "0 4px 16px rgba(0, 0, 0, 0.08)",
'--l-bg-card': 'rgba(255, 255, 255, 0.85)', "--l-bg-card": "rgba(255, 255, 255, 0.85)",
'--l-gradient-primary': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', "--l-gradient-primary": "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
}, },
portrait: { portrait: {
// 竖屏专用 // 竖屏专用
'--module-box-height': 'auto', "--module-box-height": "auto",
'--tool-box-min-height': '280px', "--tool-box-min-height": "280px",
'--entrance-icon-size': '52px', "--entrance-icon-size": "52px",
}, },
landscape: { landscape: {
// 横屏专用 // 横屏专用
'--module-box-height': '320px', "--module-box-height": "320px",
'--tool-box-height': '280px', "--tool-box-height": "280px",
'--entrance-icon-size': '56px', "--entrance-icon-size": "56px",
}, },
resolutions: { resolutions: {
// 精确分辨率适配(优先级最高) // 精确分辨率适配(优先级最高)
'landscape-1024x768': { "landscape-1024x768": {
'--module-box-height': '360px', "--module-box-height": "360px",
'--entrance-icon-size': '60px', "--entrance-icon-size": "60px",
}, },
} },
} };
``` ```
## 使用方式 ## 使用方式
...@@ -74,7 +76,7 @@ export default { ...@@ -74,7 +76,7 @@ export default {
### 1. 在组件中导入配置 ### 1. 在组件中导入配置
```typescript ```typescript
import pageVars from "./styles/index.vars" import pageVars from "./styles/index.vars";
``` ```
### 2. 在 SCSS 中使用 CSS 变量 ### 2. 在 SCSS 中使用 CSS 变量
...@@ -89,12 +91,14 @@ import pageVars from "./styles/index.vars" ...@@ -89,12 +91,14 @@ import pageVars from "./styles/index.vars"
### 3. 无需任何 JavaScript 逻辑 ### 3. 无需任何 JavaScript 逻辑
❌ **不需要**: ❌ **不需要**:
- 监听屏幕旋转事件 - 监听屏幕旋转事件
- 手动计算样式 - 手动计算样式
- 条件判断横竖屏 - 条件判断横竖屏
- 动态绑定 `:style` - 动态绑定 `:style`
✅ **只需要**: ✅ **只需要**:
- 定义 CSS 变量 - 定义 CSS 变量
- 在 SCSS 中引用 - 在 SCSS 中引用
...@@ -103,8 +107,9 @@ import pageVars from "./styles/index.vars" ...@@ -103,8 +107,9 @@ import pageVars from "./styles/index.vars"
HomeFrame 布局相关变量简洁命名,间距和字体保留 `l-` 前缀: HomeFrame 布局相关变量简洁命名,间距和字体保留 `l-` 前缀:
### 基础变量 ### 基础变量
| 变量名 | 说明 | 示例值 | | 变量名 | 说明 | 示例值 |
|--------|------|--------| | -------------------------- | ------------------------ | ---------------- |
| `--module-box-height` | 产品介绍模块高度 | `320px` / `auto` | | `--module-box-height` | 产品介绍模块高度 | `320px` / `auto` |
| `--tool-box-height` | 展业工具模块高度(横屏) | `280px` | | `--tool-box-height` | 展业工具模块高度(横屏) | `280px` |
| `--tool-box-min-height` | 展业工具最小高度(竖屏) | `280px` | | `--tool-box-min-height` | 展业工具最小高度(竖屏) | `280px` |
...@@ -118,8 +123,9 @@ HomeFrame 布局相关变量简洁命名,间距和字体保留 `l-` 前缀: ...@@ -118,8 +123,9 @@ HomeFrame 布局相关变量简洁命名,间距和字体保留 `l-` 前缀:
| `--entrance-item-gap` | Entrance 项目间距 | `20px` / `24px` | | `--entrance-item-gap` | Entrance 项目间距 | `20px` / `24px` |
### 设计系统变量 ### 设计系统变量
| 变量名 | 说明 | 示例值 | | 变量名 | 说明 | 示例值 |
|--------|------|--------| | ---------------- | ---------------------------------- | --------------------------- |
| `--l-spacing-*` | 间距变量 (xs/sm/md/lg/xl/2xl/3xl) | `4px` ~ `32px` | | `--l-spacing-*` | 间距变量 (xs/sm/md/lg/xl/2xl/3xl) | `4px` ~ `32px` |
| `--l-font-*` | 字体变量 (xs/sm/md/lg) | `12px` ~ `18px` | | `--l-font-*` | 字体变量 (xs/sm/md/lg) | `12px` ~ `18px` |
| `--l-radius-*` | 圆角变量 (sm/md/lg/xl) | `8px` ~ `20px` | | `--l-radius-*` | 圆角变量 (sm/md/lg/xl) | `8px` ~ `20px` |
...@@ -145,6 +151,7 @@ resolutions[方向-分辨率] > portrait/landscape > common ...@@ -145,6 +151,7 @@ resolutions[方向-分辨率] > portrait/landscape > common
## 注意事项 ## 注意事项
⚠️ **重要**: ⚠️ **重要**:
- 变量名必须与 `index.vars.uts` 中定义的完全一致 - 变量名必须与 `index.vars.uts` 中定义的完全一致
- 分辨率 key 格式:`{方向}-{宽}x{高}`,如 `portrait-393x816` - 分辨率 key 格式:`{方向}-{宽}x{高}`,如 `portrait-393x816`
- UTS 对象属性间必须用逗号分隔 - UTS 对象属性间必须用逗号分隔
......
...@@ -124,7 +124,6 @@ ...@@ -124,7 +124,6 @@
padding-bottom: var(--l-spacing-lg); padding-bottom: var(--l-spacing-lg);
} }
// 大屏平板横屏 (1174x768) 特殊优化 // 大屏平板横屏 (1174x768) 特殊优化
.layout-landscape-1174x768 .right-content { .layout-landscape-1174x768 .right-content {
padding-top: 4px; padding-top: 4px;
...@@ -319,7 +318,7 @@ ...@@ -319,7 +318,7 @@
} }
.title-text::before { .title-text::before {
content: ''; content: "";
position: absolute; position: absolute;
left: -12px; left: -12px;
top: 50%; top: 50%;
...@@ -434,13 +433,12 @@ ...@@ -434,13 +433,12 @@
} }
// ===== HomeFrame Tabbar( .hf-landscape-column, // ===== HomeFrame Tabbar( .hf-landscape-column,
.user-box, .user-box,
.landscape-tabbar-wrap, .landscape-tabbar-wrap,
.home-tabbar-footer { .home-tabbar-footer {
position: relative; position: relative;
z-index: 1; z-index: 1;
} }
.home-tabbar-landscape { .home-tabbar-landscape {
min-height: 0; min-height: 0;
......
...@@ -11,21 +11,22 @@ ...@@ -11,21 +11,22 @@
**使用示例:** **使用示例:**
```typescript ```typescript
import { useRecorder } from '@/composables/useRecorder' import { useRecorder } from "@/composables/useRecorder";
const { isRecording, startAudio, stopAudio } = useRecorder() const { isRecording, startAudio, stopAudio } = useRecorder();
// 开始录音 // 开始录音
startAudio() startAudio();
// 停止录音 // 停止录音
stopAudio() stopAudio();
// 强制停止录音 // 强制停止录音
stopAudio(true) stopAudio(true);
``` ```
**API:** **API:**
- `isRecording: Ref<boolean>` - 是否正在录音 - `isRecording: Ref<boolean>` - 是否正在录音
- `startAudio(): void` - 开始录音 - `startAudio(): void` - 开始录音
- `stopAudio(force?: boolean): void` - 停止录音 - `stopAudio(force?: boolean): void` - 停止录音
...@@ -37,21 +38,22 @@ stopAudio(true) ...@@ -37,21 +38,22 @@ stopAudio(true)
**使用示例:** **使用示例:**
```typescript ```typescript
import { useUploader } from '@/composables/useUploader' import { useUploader } from "@/composables/useUploader";
const { uploadQueue, isUploading, addToQueue, upload, clearQueue } = useUploader() const { uploadQueue, isUploading, addToQueue, upload, clearQueue } = useUploader();
// 添加文件到队列 // 添加文件到队列
addToQueue('/path/to/file.mp3') addToQueue("/path/to/file.mp3");
// 执行上传 // 执行上传
await upload() await upload();
// 清空队列 // 清空队列
clearQueue() clearQueue();
``` ```
**API:** **API:**
- `uploadQueue: Ref<string[]>` - 上传队列 - `uploadQueue: Ref<string[]>` - 上传队列
- `isUploading: Ref<boolean>` - 是否正在上传 - `isUploading: Ref<boolean>` - 是否正在上传
- `addToQueue(filePath: string): void` - 添加文件到队列 - `addToQueue(filePath: string): void` - 添加文件到队列
...@@ -65,21 +67,22 @@ clearQueue() ...@@ -65,21 +67,22 @@ clearQueue()
**使用示例:** **使用示例:**
```typescript ```typescript
import { usePermission } from '@/composables/usePermission' import { usePermission } from "@/composables/usePermission";
const { checkMicrophonePermission, checkStoragePermission, requestPermission } = usePermission() const { checkMicrophonePermission, checkStoragePermission, requestPermission } = usePermission();
// 检查麦克风权限 // 检查麦克风权限
const hasMicPermission = await checkMicrophonePermission() const hasMicPermission = await checkMicrophonePermission();
// 检查存储权限 // 检查存储权限
const hasStoragePermission = await checkStoragePermission() const hasStoragePermission = await checkStoragePermission();
// 请求权限 // 请求权限
const granted = await requestPermission('microphone') const granted = await requestPermission("microphone");
``` ```
**API:** **API:**
- `checkMicrophonePermission(): Promise<boolean>` - 检查麦克风权限 - `checkMicrophonePermission(): Promise<boolean>` - 检查麦克风权限
- `checkStoragePermission(): Promise<boolean>` - 检查存储权限 - `checkStoragePermission(): Promise<boolean>` - 检查存储权限
- `requestPermission(permissionType: string): Promise<boolean>` - 请求权限 - `requestPermission(permissionType: string): Promise<boolean>` - 请求权限
...@@ -91,31 +94,26 @@ const granted = await requestPermission('microphone') ...@@ -91,31 +94,26 @@ const granted = await requestPermission('microphone')
**使用示例:** **使用示例:**
```typescript ```typescript
import { useReception } from '@/composables/useReception' import { useReception } from "@/composables/useReception";
const { const { receptionStatus, showFinishDialog, startReception, finishReception, closeFinishDialog, clearHistory } =
receptionStatus, useReception();
showFinishDialog,
startReception,
finishReception,
closeFinishDialog,
clearHistory
} = useReception()
// 开始接待 // 开始接待
startReception() startReception();
// 完成接待 // 完成接待
finishReception() finishReception();
// 关闭完成弹窗 // 关闭完成弹窗
closeFinishDialog() closeFinishDialog();
// 清除历史 // 清除历史
clearHistory() clearHistory();
``` ```
**API:** **API:**
- `receptionStatus: Ref<number>` - 接待状态(0: 未开始, 1: 接待中, 2: 已完成) - `receptionStatus: Ref<number>` - 接待状态(0: 未开始, 1: 接待中, 2: 已完成)
- `showFinishDialog: Ref<boolean>` - 是否显示完成弹窗 - `showFinishDialog: Ref<boolean>` - 是否显示完成弹窗
- `startReception(): void` - 开始接待 - `startReception(): void` - 开始接待
...@@ -130,20 +128,21 @@ clearHistory() ...@@ -130,20 +128,21 @@ clearHistory()
**使用示例:** **使用示例:**
```typescript ```typescript
import { useVersionCheck } from '@/composables/useVersionCheck' import { useVersionCheck } from "@/composables/useVersionCheck";
const { hasNewVersion, versionInfo, checkVersion, doUpdate } = useVersionCheck() const { hasNewVersion, versionInfo, checkVersion, doUpdate } = useVersionCheck();
// 检查版本 // 检查版本
await checkVersion() await checkVersion();
// 执行更新 // 执行更新
if (hasNewVersion.value) { if (hasNewVersion.value) {
doUpdate() doUpdate();
} }
``` ```
**API:** **API:**
- `hasNewVersion: Ref<boolean>` - 是否有新版本 - `hasNewVersion: Ref<boolean>` - 是否有新版本
- `versionInfo: Ref<UTSJSONObject | null>` - 版本信息 - `versionInfo: Ref<UTSJSONObject | null>` - 版本信息
- `checkVersion(): Promise<void>` - 检查版本更新 - `checkVersion(): Promise<void>` - 检查版本更新
......
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
### 3. 变量列表 ### 3. 变量列表
| 变量 | 说明 | 默认值(1024基准) | | 变量 | 说明 | 默认值(1024基准) |
|------|------|-----------------| | --------------- | ---- | ---------------- |
| --l-spacing-xs | 间距 | 8px | | --l-spacing-xs | 间距 | 8px |
| --l-spacing-sm | 间距 | 12px | | --l-spacing-sm | 间距 | 12px |
| --l-spacing-md | 间距 | 16px | | --l-spacing-md | 间距 | 16px |
...@@ -63,18 +63,18 @@ ...@@ -63,18 +63,18 @@
### 4. JS 中按设计稿缩放 ### 4. JS 中按设计稿缩放
```typescript ```typescript
import { useLayout } from '@/composables/useLayout' import { useLayout } from "@/composables/useLayout";
const { scaleSize } = useLayout() const { scaleSize } = useLayout();
// 设计稿 200px 宽的按钮 // 设计稿 200px 宽的按钮
const btnWidth = scaleSize(200) const btnWidth = scaleSize(200);
``` ```
### 5. 模式判断(预留) ### 5. 模式判断(预留)
```typescript ```typescript
const { isPad, isPortrait, isDesktop } = useLayout() const { isPad, isPortrait, isDesktop } = useLayout();
if (isPad.value) { if (isPad.value) {
// pad 布局 // pad 布局
......
...@@ -5,11 +5,12 @@ ...@@ -5,11 +5,12 @@
## 1. 核心机制 ## 1. 核心机制
系统基于 **“配置对象 (Configuration Object)”** 模式: 系统基于 **“配置对象 (Configuration Object)”** 模式:
1. **自动检测**:App 启动或窗口调整时,自动获取屏幕宽高。 1. **自动检测**:App 启动或窗口调整时,自动获取屏幕宽高。
2. **键值匹配**:生成如 `1024x768` 的 Key。 2. **键值匹配**:生成如 `1024x768` 的 Key。
3. **智能加载**: 3. **智能加载**:
* 优先加载对应分辨率的专用配置(如 `landscape/1024x768`)。 - 优先加载对应分辨率的专用配置(如 `landscape/1024x768`)。
* 未匹配则降级使用兜底配置(`landscape/common` 或 `portrait/common`)。 - 未匹配则降级使用兜底配置(`landscape/common` 或 `portrait/common`)。
4. **响应式更新**:配置对象是 Vue Reactive 的,分辨率变化时页面自动更新。 4. **响应式更新**:配置对象是 Vue Reactive 的,分辨率变化时页面自动更新。
## 2. 目录结构 ## 2. 目录结构
...@@ -53,11 +54,10 @@ config/resolution-adapt/ ...@@ -53,11 +54,10 @@ config/resolution-adapt/
</view> </view>
<!-- 方式 B: JS 动态样式 (Style Binding) --> <!-- 方式 B: JS 动态样式 (Style Binding) -->
<view class="dynamic-box" <view class="dynamic-box" :style="{ paddingLeft: $resState.config.demo.paddingLeft }">
:style="{ paddingLeft: $resState.config.demo.paddingLeft }">
<!-- 动态图片:使用全局方法 $getResImg 自动选择 @2x/@3x 图片 --> <!-- 动态图片:使用全局方法 $getResImg 自动选择 @2x/@3x 图片 -->
<image :src="$getResImg($resState.config.demo.heroImageSrc)" <image
:src="$getResImg($resState.config.demo.heroImageSrc)"
:style="{ width: $resState.config.demo.heroImageWidth }" :style="{ width: $resState.config.demo.heroImageWidth }"
mode="widthFix" /> mode="widthFix" />
</view> </view>
...@@ -65,7 +65,7 @@ config/resolution-adapt/ ...@@ -65,7 +65,7 @@ config/resolution-adapt/
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
// 无需 import 任何分辨率适配相关的代码! // 无需 import 任何分辨率适配相关的代码!
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
...@@ -144,10 +144,10 @@ heroImageSrc: { ...@@ -144,10 +144,10 @@ heroImageSrc: {
```typescript ```typescript
// config/resolution-adapt/registry.uts // config/resolution-adapt/registry.uts
import { config as ls_1280 } from './landscape/1280x800/index.uts' import { config as ls_1280 } from "./landscape/1280x800/index.uts";
const landscapeConfigs = { const landscapeConfigs = {
// ... // ...
"1280x800": ls_1280 // 新增 "1280x800": ls_1280, // 新增
} as UTSJSONObject } as UTSJSONObject;
``` ```
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
## 一、Store 访问 ## 一、Store 访问
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| | ------------------------------- | --------------------------------------------------------------- |
| `store.state.boutique` (弱类型) | **直接导入 state**: `import { state } from '@/store/index.uts'` | | `store.state.boutique` (弱类型) | **直接导入 state**: `import { state } from '@/store/index.uts'` |
| `store.state.user.xxx` | `state.user.xxx` (强类型访问) | | `store.state.user.xxx` | `state.user.xxx` (强类型访问) |
| 直接 `this.$store.state` | Options API 中使用 `mapState` | | 直接 `this.$store.state` | Options API 中使用 `mapState` |
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
## 二、Ref 初始化 ## 二、Ref 初始化
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| | -------------------------- | -------- | ------------ |
| `ref(null as any)` | `ref<any | null>(null)` | | `ref(null as any)` | `ref<any | null>(null)` |
| `ref<Comp>(null)` 组件 ref | `ref<any | null>(null)` | | `ref<Comp>(null)` 组件 ref | `ref<any | null>(null)` |
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
## 三、模板 v-for 中的 item ## 三、模板 v-for 中的 item
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| | -------------------------------------- | ---------------------------------- |
| `{{ item['bannerImg'] }}` | `{{ getPkg(item, 'bannerImg') }}` | | `{{ item['bannerImg'] }}` | `{{ getPkg(item, 'bannerImg') }}` |
| `:src="item.bannerImg"`(item 为 any) | `:src="getPkg(item, 'bannerImg')"` | | `:src="item.bannerImg"`(item 为 any) | `:src="getPkg(item, 'bannerImg')"` |
...@@ -51,7 +51,7 @@ function getPkg(item: any, key: string): any { ...@@ -51,7 +51,7 @@ function getPkg(item: any, key: string): any {
## 四、数字 key 的对象映射 ## 四、数字 key 的对象映射
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| | ------------------------------------------------- | ------------------------------- | ----- |
| `Record<number, X>` + `{ 1: {...}, 0: {...} }` | 用函数映射 | | `Record<number, X>` + `{ 1: {...}, 0: {...} }` | 用函数映射 |
| `const map = { 1: a, 0: b } as Record<number, X>` | `function getXxx(id: number): X | null` | | `const map = { 1: a, 0: b } as Record<number, X>` | `function getXxx(id: number): X | null` |
...@@ -70,7 +70,7 @@ function getSceneTypeItem(sceneId: number): SceneTypeItem | null { ...@@ -70,7 +70,7 @@ function getSceneTypeItem(sceneId: number): SceneTypeItem | null {
## 五、数字格式化 ## 五、数字格式化
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| | ---------------------------- | ---------------------------------------------- |
| `Number(x).toLocaleString()` | `parseFloat((x as any).toString()).toString()` | | `Number(x).toLocaleString()` | `parseFloat((x as any).toString()).toString()` |
| `x.toLocaleString()` | 同上或自定义 formatNumber | | `x.toLocaleString()` | 同上或自定义 formatNumber |
...@@ -81,7 +81,7 @@ function getSceneTypeItem(sceneId: number): SceneTypeItem | null { ...@@ -81,7 +81,7 @@ function getSceneTypeItem(sceneId: number): SceneTypeItem | null {
## 六、Storage / JSON 解析 ## 六、Storage / JSON 解析
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| | ---------------------- | -------------------------- |
| 直接 `JSON.parse(raw)` | 用 `parseStorageJson(key)` | | 直接 `JSON.parse(raw)` | 用 `parseStorageJson(key)` |
| `JSON.parse("")` | 判空 + try-catch | | `JSON.parse("")` | 判空 + try-catch |
......
<!DOCTYPE html> <!doctype html>
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<script> <script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || var coverSupport =
CSS.supports('top: constant(a)')) "CSS" in window &&
typeof CSS.supports === "function" &&
(CSS.supports("top: env(a)") || CSS.supports("top: constant(a)"));
document.write( document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />') (coverSupport ? ", viewport-fit=cover" : "") +
'" />',
);
</script> </script>
<title></title> <title></title>
<!--preload-links--> <!--preload-links-->
......
...@@ -4,8 +4,7 @@ ...@@ -4,8 +4,7 @@
"description": "", "description": "",
"versionName": "1.0.0", "versionName": "1.0.0",
"versionCode": "127", "versionCode": "127",
"uni-app-x": { "uni-app-x": {},
},
"quickapp": {}, "quickapp": {},
"mp-weixin": { "mp-weixin": {
"appid": "", "appid": "",
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
// 添加装饰性渐变光晕效果 // 添加装饰性渐变光晕效果
&::before { &::before {
content: ''; content: "";
position: absolute; position: absolute;
top: -50%; top: -50%;
right: -20%; right: -20%;
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
} }
&::after { &::after {
content: ''; content: "";
position: absolute; position: absolute;
bottom: -30%; bottom: -30%;
left: -10%; left: -10%;
......
...@@ -9,22 +9,23 @@ ...@@ -9,22 +9,23 @@
```typescript ```typescript
export default { export default {
common: { common: {
'--primary-color': '#1677ff', // 所有场景通用 "--primary-color": "#1677ff", // 所有场景通用
}, },
portrait: { portrait: {
'--padding': '16px', // 竖屏专用 "--padding": "16px", // 竖屏专用
'--columns': '2', "--columns": "2",
}, },
landscape: { landscape: {
'--padding': '32px', // 横屏专用 "--padding": "32px", // 横屏专用
'--columns': '4', "--columns": "4",
}, },
resolutions: { resolutions: {
'portrait-393x816': { // 精确分辨率适配 "portrait-393x816": {
'--padding': '20px', // 精确分辨率适配
"--padding": "20px",
}, },
} },
} };
``` ```
### 2. 在页面中使用 ### 2. 在页面中使用
...@@ -53,7 +54,7 @@ import pageVars from './styles/index.vars' ...@@ -53,7 +54,7 @@ import pageVars from './styles/index.vars'
## 配置层级说明 ## 配置层级说明
| 层级 | 优先级 | 使用场景 | | 层级 | 优先级 | 使用场景 |
|------|--------|----------| | -------------------------- | ------ | ------------------ |
| `common` | 低 | 所有场景相同的样式 | | `common` | 低 | 所有场景相同的样式 |
| `portrait/landscape` | 中 | 横竖屏不同的布局 | | `portrait/landscape` | 中 | 横竖屏不同的布局 |
| `resolutions[方向-分辨率]` | 高 | 特定设备精确适配 | | `resolutions[方向-分辨率]` | 高 | 特定设备精确适配 |
......
.adapter{ .adapter {
color:var(--adapter-color); color: var(--adapter-color);
font-size: var(--adapter-fontsize); font-size: var(--adapter-fontsize);
} }
.test-view{ .test-view {
height: var(--test-view-height); height: var(--test-view-height);
width: var(--test-view-width); width: var(--test-view-width);
border: var(--test-view-border-width, 1px) var(--test-view-border-style, solid) var(--test-view-border-color, transparent); border: var(--test-view-border-width, 1px) var(--test-view-border-style, solid)
var(--test-view-border-color, transparent);
background-color: var(--test-view-bg, transparent); background-color: var(--test-view-bg, transparent);
border-radius: var(--test-view-border-radius); border-radius: var(--test-view-border-radius);
display: flex; display: flex;
......
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
flex-direction: column; flex-direction: column;
border-radius: 16px; border-radius: 16px;
background: rgba(255, 255, 255, 0.86); background: rgba(255, 255, 255, 0.86);
box-shadow: 0 12px 32px rgba(15, 23, 42, 0.10); box-shadow: 0 12px 32px rgba(15, 23, 42, 0.1);
overflow: hidden; overflow: hidden;
} }
...@@ -101,7 +101,7 @@ ...@@ -101,7 +101,7 @@
height: 100%; height: 100%;
border-radius: 10px; border-radius: 10px;
overflow: hidden; overflow: hidden;
box-shadow: 0 8px 18px rgba(15, 23, 42, 0.10); box-shadow: 0 8px 18px rgba(15, 23, 42, 0.1);
} }
.equity-swiper-overlay { .equity-swiper-overlay {
...@@ -115,7 +115,7 @@ ...@@ -115,7 +115,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: flex-end; justify-content: flex-end;
background-image: linear-gradient(to top, rgba(30, 58, 138, 0.56) 0%, rgba(30, 58, 138, 0.0) 26%); background-image: linear-gradient(to top, rgba(30, 58, 138, 0.56) 0%, rgba(30, 58, 138, 0) 26%);
border-radius: 10px; border-radius: 10px;
} }
......
...@@ -97,7 +97,7 @@ ...@@ -97,7 +97,7 @@
// font-size: 17px; // font-size: 17px;
// margin-top: 8px; // margin-top: 8px;
// } // }
} }
:deep(.layout-landscape-1174x768) .equity-page { :deep(.layout-landscape-1174x768) .equity-page {
.swiper-custom-content { .swiper-custom-content {
......
.adapter{ .adapter {
color:var(--adapter-color); color: var(--adapter-color);
font-size: var(--adapter-fontsize); font-size: var(--adapter-fontsize);
} }
.test-view{ .test-view {
height: var(--test-view-height); height: var(--test-view-height);
background-color: var(--test-view-bg, transparent); background-color: var(--test-view-bg, transparent);
} }
.reception-tabs-container{ .reception-tabs-container {
padding: var(--reception-tabs-container-padding); padding: var(--reception-tabs-container-padding);
margin-top: var(--reception-tabs-container-margin-top); margin-top: var(--reception-tabs-container-margin-top);
background-color: var(--reception-tabs-container-bgc); background-color: var(--reception-tabs-container-bgc);
......
{ {
"targets": [ "targets": ["APP-ANDROID"]
"APP-ANDROID"
]
} }
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
## 📦 可用服务列表 ## 📦 可用服务列表
| 服务名称 | 类型 | 描述 | 使用场景 | | 服务名称 | 类型 | 描述 | 使用场景 |
|---------|------|------|---------| | ---------------- | ------------------- | -------------------------- | -------------------------- |
| `logger` | `Logger` | 日志记录与上传服务 | 记录应用日志、错误追踪 | | `logger` | `Logger` | 日志记录与上传服务 | 记录应用日志、错误追踪 |
| `dbRecord` | `DBRecord` | 数据库记录管理服务 | 接待记录的 CRUD 操作 | | `dbRecord` | `DBRecord` | 数据库记录管理服务 | 接待记录的 CRUD 操作 |
| `fileUpload` | `FileUploadService` | 文件上传服务(支持多策略) | 上传图片、音频等到 OSS | | `fileUpload` | `FileUploadService` | 文件上传服务(支持多策略) | 上传图片、音频等到 OSS |
...@@ -36,7 +36,7 @@ services.logger.info("页面加载", "App"); ...@@ -36,7 +36,7 @@ services.logger.info("页面加载", "App");
// 使用数据库服务 // 使用数据库服务
await services.dbRecord.updateRecord({ await services.dbRecord.updateRecord({
id: "123", id: "123",
status: "completed" status: "completed",
}); });
// 使用文件上传服务 // 使用文件上传服务
...@@ -50,6 +50,7 @@ services.timeoutService.start(); ...@@ -50,6 +50,7 @@ services.timeoutService.start();
``` ```
**优点:** **优点:**
- ✅ 统一管理,代码风格一致 - ✅ 统一管理,代码风格一致
- ✅ IDE 智能提示完整 - ✅ IDE 智能提示完整
- ✅ 适用于所有场景(业务代码和子服务模块) - ✅ 适用于所有场景(业务代码和子服务模块)
...@@ -67,10 +68,12 @@ const result = await fileUpload.uploadFile(filePath); ...@@ -67,10 +68,12 @@ const result = await fileUpload.uploadFile(filePath);
``` ```
**优点:** **优点:**
- ✅ 代码更简洁 - ✅ 代码更简洁
- ✅ 按需导入,语义清晰 - ✅ 按需导入,语义清晰
**⚠️ 注意事项:** **⚠️ 注意事项:**
- ❌ **仅限业务代码使用**(pages/, components/ 目录) - ❌ **仅限业务代码使用**(pages/, components/ 目录)
- ❌ **子服务模块不能使用**(会造成循环依赖) - ❌ **子服务模块不能使用**(会造成循环依赖)
...@@ -150,6 +153,7 @@ services.logger.debug("请求参数:" + JSON.stringify(params), "API"); ...@@ -150,6 +153,7 @@ services.logger.debug("请求参数:" + JSON.stringify(params), "API");
``` ```
**在子服务模块中使用:** **在子服务模块中使用:**
```typescript ```typescript
// recorder/AudioManager.uts // recorder/AudioManager.uts
import { Logger } from "../logger/LoggerCore"; import { Logger } from "../logger/LoggerCore";
...@@ -173,7 +177,7 @@ const records = await services.dbRecord.getCompletedRecords(); ...@@ -173,7 +177,7 @@ const records = await services.dbRecord.getCompletedRecords();
await services.dbRecord.updateRecord({ await services.dbRecord.updateRecord({
id: "123", id: "123",
receptionStatus: 1, receptionStatus: 1,
receptionEndTime: new Date().toISOString() receptionEndTime: new Date().toISOString(),
}); });
// 删除记录 // 删除记录
...@@ -191,7 +195,7 @@ import services from "@/services"; ...@@ -191,7 +195,7 @@ import services from "@/services";
// 上传文件 // 上传文件
const result = await services.fileUpload.upload({ const result = await services.fileUpload.upload({
filePath: "/path/to/file.mp3", filePath: "/path/to/file.mp3",
fileName: "recording.mp3" fileName: "recording.mp3",
}); });
console.log("上传成功:", result.url); console.log("上传成功:", result.url);
...@@ -212,7 +216,7 @@ await services.recordSave.save({ ...@@ -212,7 +216,7 @@ await services.recordSave.save({
receptionStartTime: new Date().toISOString(), receptionStartTime: new Date().toISOString(),
receptionEndTime: new Date().toISOString(), receptionEndTime: new Date().toISOString(),
receptionStatus: 1, receptionStatus: 1,
recordUrlList: ["url1", "url2"] recordUrlList: ["url1", "url2"],
}); });
``` ```
...@@ -372,7 +376,7 @@ async function handleReception() { ...@@ -372,7 +376,7 @@ async function handleReception() {
// 可以继续处理 // 可以继续处理
uni.showToast({ uni.showToast({
title: "录音启动失败", title: "录音启动失败",
icon: "none" icon: "none",
}); });
} }
} }
......
...@@ -8,16 +8,16 @@ ...@@ -8,16 +8,16 @@
```typescript ```typescript
// 直接导入单例对象 // 直接导入单例对象
import { recordService } from '@/services/recorder/index.uts' import { recordService } from "@/services/recorder/index.uts";
``` ```
### 开始接待/录音 ### 开始接待/录音
```typescript ```typescript
// 开始录音 (自动请求权限) // 开始录音 (自动请求权限)
const success = await recordService.startAudio() const success = await recordService.startAudio();
if (success) { if (success) {
console.log('录音已开始') console.log("录音已开始");
} }
``` ```
...@@ -25,10 +25,10 @@ if (success) { ...@@ -25,10 +25,10 @@ if (success) {
```typescript ```typescript
// 结束录音并保存记录 // 结束录音并保存记录
await recordService.stopAudio() await recordService.stopAudio();
// 仅结束录音,不保存记录 (例如用户取消) // 仅结束录音,不保存记录 (例如用户取消)
await recordService.stopAudio(true) await recordService.stopAudio(true);
``` ```
## 2. 业务数据更新 ## 2. 业务数据更新
...@@ -39,38 +39,27 @@ await recordService.stopAudio(true) ...@@ -39,38 +39,27 @@ await recordService.stopAudio(true)
```typescript ```typescript
const customerInfo = { const customerInfo = {
customerName: '张三', customerName: "张三",
phoneNumber: '13800138000', phoneNumber: "13800138000",
carModel: 'Model Y' carModel: "Model Y",
} };
// updateBusinessData(类型,数据) // updateBusinessData(类型,数据)
recordService.updateBusinessData( recordService.updateBusinessData("customer", customerInfo);
'customer',
customerInfo
)
``` ```
### 更新接待状态 ### 更新接待状态
```typescript ```typescript
// 状态 '1' 表示接待中,'0' 表示结束 // 状态 '1' 表示接待中,'0' 表示结束
recordService.updateBusinessData( recordService.updateBusinessData("status", "1");
'status',
'1'
)
``` ```
### 更新物料/轨迹点 ### 更新物料/轨迹点
```typescript ```typescript
const points = [ const points = [{ x: 100, y: 200, time: 1234567890 }];
{ x: 100, y: 200, time: 1234567890 } recordService.updateBusinessData("material", points);
]
recordService.updateBusinessData(
'material',
points
)
``` ```
## 3. 获取业务数据 ## 3. 获取业务数据
...@@ -79,8 +68,8 @@ recordService.updateBusinessData( ...@@ -79,8 +68,8 @@ recordService.updateBusinessData(
```typescript ```typescript
// 或者使用通用方法获取特定类型数据 // 或者使用通用方法获取特定类型数据
const materialData = await recordService.getBusinessData('material') const materialData = await recordService.getBusinessData("material");
console.log('物料数据:', materialData?.receptionCustomerMaterialPointList) console.log("物料数据:", materialData?.receptionCustomerMaterialPointList);
``` ```
### 注意事项 ### 注意事项
...@@ -100,9 +89,8 @@ console.log('物料数据:', materialData?.receptionCustomerMaterialPointList) ...@@ -100,9 +89,8 @@ console.log('物料数据:', materialData?.receptionCustomerMaterialPointList)
import { IRecorderStrategy } from "../types/strategy.uts"; import { IRecorderStrategy } from "../types/strategy.uts";
export class RealEstateStrategy implements IRecorderStrategy { export class RealEstateStrategy implements IRecorderStrategy {
getName(): string { getName(): string {
return "RealEstateStrategy" return "RealEstateStrategy";
} }
// 1. 定义该业务需要的数据库字段 // 1. 定义该业务需要的数据库字段
...@@ -110,29 +98,29 @@ export class RealEstateStrategy implements IRecorderStrategy { ...@@ -110,29 +98,29 @@ export class RealEstateStrategy implements IRecorderStrategy {
return [ return [
"houseType TEXT", // 户型 "houseType TEXT", // 户型
"area INTEGER", // 面积 "area INTEGER", // 面积
"budget TEXT" // 预算 "budget TEXT", // 预算
] ];
} }
// 2. 指定需要解析为 JSON 的字段 // 2. 指定需要解析为 JSON 的字段
getJsonFields(): string[] { getJsonFields(): string[] {
return [ return [
"houseInfo", // 房屋信息 "houseInfo", // 房屋信息
"customerPreference" // 客户偏好 "customerPreference", // 客户偏好
] ];
} }
// 3. 处理业务数据转换 // 3. 处理业务数据转换
handle(type: string, data: any | null, recordId: string): null | UTSJSONObject { handle(type: string, data: any | null, recordId: string): null | UTSJSONObject {
// 根据 type 处理 data,返回存入 DB 的 JSON 对象 // 根据 type 处理 data,返回存入 DB 的 JSON 对象
if (type == 'house_info') { if (type == "house_info") {
const info = data as UTSJSONObject const info = data as UTSJSONObject;
return { return {
houseType: info['type'], houseType: info["type"],
area: info['area'] area: info["area"],
};
} }
} return null;
return null
} }
} }
``` ```
...@@ -142,15 +130,16 @@ export class RealEstateStrategy implements IRecorderStrategy { ...@@ -142,15 +130,16 @@ export class RealEstateStrategy implements IRecorderStrategy {
在业务初始化时调用: 在业务初始化时调用:
```typescript ```typescript
import { RealEstateStrategy } from '@/composables/recorder/strategies/RealEstateStrategy.uts' import { RealEstateStrategy } from "@/composables/recorder/strategies/RealEstateStrategy.uts";
import { recordService } from '@/composables/recorder/index.uts' import { recordService } from "@/composables/recorder/index.uts";
// 切换到房产销售策略 // 切换到房产销售策略
const strategy = new RealEstateStrategy() const strategy = new RealEstateStrategy();
recordService.setStrategy(strategy) recordService.setStrategy(strategy);
``` ```
切换策略后: 切换策略后:
1. `DBRecord` 会自动检查并创建新的数据库字段。 1. `DBRecord` 会自动检查并创建新的数据库字段。
2. `RecordService` 会使用新策略的 `handle` 方法处理数据。 2. `RecordService` 会使用新策略的 `handle` 方法处理数据。
...@@ -216,11 +205,11 @@ recordService.setStrategy(strategy) ...@@ -216,11 +205,11 @@ recordService.setStrategy(strategy)
```typescript ```typescript
// ✅ 推荐:在用户输入时立即更新 // ✅ 推荐:在用户输入时立即更新
inputElement.on('change', (e) => { inputElement.on("change", (e) => {
recordService.updateBusinessData('customer', { recordService.updateBusinessData("customer", {
customerName: e.target.value customerName: e.target.value,
}) });
}) });
// ❌ 避免:集中批量更新,可能导致数据丢失 // ❌ 避免:集中批量更新,可能导致数据丢失
``` ```
...@@ -228,9 +217,8 @@ inputElement.on('change', (e) => { ...@@ -228,9 +217,8 @@ inputElement.on('change', (e) => {
### 7.2 数据获取选择 ### 7.2 数据获取选择
```typescript ```typescript
// ✅ 通用方法(支持所有类型) // ✅ 通用方法(支持所有类型)
const data = await recordService.getBusinessData('material') const data = await recordService.getBusinessData("material");
``` ```
### 7.3 策略切换 ### 7.3 策略切换
...@@ -238,9 +226,9 @@ const data = await recordService.getBusinessData('material') ...@@ -238,9 +226,9 @@ const data = await recordService.getBusinessData('material')
```typescript ```typescript
// ✅ 在应用初始化时切换策略 // ✅ 在应用初始化时切换策略
onLaunch(() => { onLaunch(() => {
const strategy = new CustomStrategy() const strategy = new CustomStrategy();
recordService.setStrategy(strategy) recordService.setStrategy(strategy);
}) });
// ❌ 避免在接待过程中切换策略 // ❌ 避免在接待过程中切换策略
``` ```
...@@ -250,5 +238,3 @@ onLaunch(() => { ...@@ -250,5 +238,3 @@ onLaunch(() => {
1. 在策略的 `getTableColumns()` 中声明字段 1. 在策略的 `getTableColumns()` 中声明字段
2. 在 `getJsonFields()` 中声明需要 JSON 解析的字段 2. 在 `getJsonFields()` 中声明需要 JSON 解析的字段
3. 在 `handle()` 中实现数据处理逻辑 3. 在 `handle()` 中实现数据处理逻辑
...@@ -66,33 +66,33 @@ export const actions = { ...@@ -66,33 +66,33 @@ export const actions = {
// 逐个属性赋值 (推荐,类型安全) // 逐个属性赋值 (推荐,类型安全)
const s = state as UserStateType; const s = state as UserStateType;
if (data['name'] != null) { if (data["name"] != null) {
s.userInfo['name'] = data['name']; s.userInfo["name"] = data["name"];
} }
// 或者整体赋值 (需确保类型匹配) // 或者整体赋值 (需确保类型匹配)
// (state as UserStateType).userInfo = data; // (state as UserStateType).userInfo = data;
return null; return null;
} },
} };
``` ```
## 如何添加新模块 ## 如何添加新模块
1. **创建模块文件**: 在 `store/modules/` 下创建 `xxx.uts`。 1. **创建模块文件**: 在 `store/modules/` 下创建 `xxx.uts`。
2. **定义 State 类**: 2. **定义 State 类**:
* 创建 `export class XxxStateType { static _C = "companion"; ... }`。 - 创建 `export class XxxStateType { static _C = "companion"; ... }`。
* 定义所有属性并赋予默认值。 - 定义所有属性并赋予默认值。
3. **导出 State**: `export const state = reactive(new XxxStateType());`。 3. **导出 State**: `export const state = reactive(new XxxStateType());`。
4. **注册模块 (`store/index.uts`)**: 4. **注册模块 (`store/index.uts`)**:
* **顶部导入**: - **顶部导入**:
```typescript ```typescript
import { state as xxxState, XxxStateType } from "@/store/modules/xxx.uts"; import { state as xxxState, XxxStateType } from "@/store/modules/xxx.uts";
import * as xxx from "@/store/modules/xxx.uts"; // 用于动态注册 actions import * as xxx from "@/store/modules/xxx.uts"; // 用于动态注册 actions
``` ```
* **添加到 `modules` 数组**: `const modules: any[] = [..., xxx];` - **添加到 `modules` 数组**: `const modules: any[] = [..., xxx];`
* **添加到 `RootState` 类**: - **添加到 `RootState` 类**:
```typescript ```typescript
export class RootState { export class RootState {
// ... // ...
...@@ -111,25 +111,25 @@ export const actions = { ...@@ -111,25 +111,25 @@ export const actions = {
### 直接导入 (推荐) ### 直接导入 (推荐)
```typescript ```typescript
import { state } from '@/store/index.uts' import { state } from "@/store/index.uts";
// 读取 // 读取
const token = state.user.token const token = state.user.token;
// 写入 (通过 dispatch) // 写入 (通过 dispatch)
import { dispatch } from '@/store/index.uts' import { dispatch } from "@/store/index.uts";
dispatch('user/setToken', 'new-token') dispatch("user/setToken", "new-token");
``` ```
### 使用 mapHelpers (Options API) ### 使用 mapHelpers (Options API)
```typescript ```typescript
import { mapState, mapGetters } from '@/store/mapHelpers.uts' import { mapState, mapGetters } from "@/store/mapHelpers.uts";
export default { export default {
computed: { computed: {
...mapState(['user']), ...mapState(["user"]),
...mapGetters(['token']) ...mapGetters(["token"]),
} },
} };
``` ```
...@@ -98,7 +98,6 @@ $uni-font-size-paragraph: 15px; ...@@ -98,7 +98,6 @@ $uni-font-size-paragraph: 15px;
} }
} }
.common-title { .common-title {
width: 100%; width: 100%;
height: 120rpx; height: 120rpx;
......
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
## 🔄 最新更新(2026-03-18) ## 🔄 最新更新(2026-03-18)
已简化 WebSocket 连接逻辑: 已简化 WebSocket 连接逻辑:
- ✅ 移除复杂的候选地址尝试 - ✅ 移除复杂的候选地址尝试
- ✅ 直接使用配置的 WebSocket 地址 - ✅ 直接使用配置的 WebSocket 地址
- ✅ 简化登录流程 - ✅ 简化登录流程
...@@ -58,9 +59,9 @@ rm -rf apps/uniappX/uniapp-x-tape/unpackage ...@@ -58,9 +59,9 @@ rm -rf apps/uniappX/uniapp-x-tape/unpackage
```typescript ```typescript
const config = { const config = {
wsUrl: 'ws://192.168.1.237:8081/ws', wsUrl: "ws://192.168.1.237:8081/ws",
token: '你的token', // ← 修改这里 token: "你的token", // ← 修改这里
deviceId: '你的deviceId' // ← 修改这里 deviceId: "你的deviceId", // ← 修改这里
}; };
``` ```
...@@ -69,7 +70,7 @@ const config = { ...@@ -69,7 +70,7 @@ const config = {
在任意页面添加: 在任意页面添加:
```typescript ```typescript
import { quickTestNativeWebSocket } from '@/ws'; import { quickTestNativeWebSocket } from "@/ws";
onReady(() => { onReady(() => {
quickTestNativeWebSocket(); quickTestNativeWebSocket();
...@@ -81,6 +82,7 @@ onReady(() => { ...@@ -81,6 +82,7 @@ onReady(() => {
## 📚 文档导航 ## 📚 文档导航
### 新手入门 ### 新手入门
1. **[简化使用说明.md](./简化使用说明.md)** - 最新简化版使用说明(推荐!) 1. **[简化使用说明.md](./简化使用说明.md)** - 最新简化版使用说明(推荐!)
2. **[快速修复指南.md](./快速修复指南.md)** - 解决运行时错误 2. **[快速修复指南.md](./快速修复指南.md)** - 解决运行时错误
3. **[故障排除.md](./故障排除.md)** - 网络连接问题排查 3. **[故障排除.md](./故障排除.md)** - 网络连接问题排查
...@@ -88,6 +90,7 @@ onReady(() => { ...@@ -88,6 +90,7 @@ onReady(() => {
5. **[使用示例.md](./使用示例.md)** - 代码使用示例 5. **[使用示例.md](./使用示例.md)** - 代码使用示例
### 技术文档 ### 技术文档
6. **[README-NATIVE-WS.md](./README-NATIVE-WS.md)** - 原生 WebSocket 使用说明 6. **[README-NATIVE-WS.md](./README-NATIVE-WS.md)** - 原生 WebSocket 使用说明
7. **[修复记录.md](./修复记录.md)** - 完整的修复记录 7. **[修复记录.md](./修复记录.md)** - 完整的修复记录
8. **[重新编译说明.md](./重新编译说明.md)** - 编译缓存清理指南 8. **[重新编译说明.md](./重新编译说明.md)** - 编译缓存清理指南
...@@ -95,25 +98,29 @@ onReady(() => { ...@@ -95,25 +98,29 @@ onReady(() => {
## 🛠️ 测试工具 ## 🛠️ 测试工具
### 1. 快速测试脚本 ### 1. 快速测试脚本
```typescript ```typescript
import { quickTestNativeWebSocket } from '@/ws'; import { quickTestNativeWebSocket } from "@/ws";
await quickTestNativeWebSocket(); await quickTestNativeWebSocket();
``` ```
### 2. 直接连接测试(推荐,跳过登录) ### 2. 直接连接测试(推荐,跳过登录)
```typescript ```typescript
import { quickTestDirectConnect } from '@/ws'; import { quickTestDirectConnect } from "@/ws";
// 修改 ws/direct-test.uts 中的 wsUrl 配置 // 修改 ws/direct-test.uts 中的 wsUrl 配置
await quickTestDirectConnect(); await quickTestDirectConnect();
``` ```
### 3. 测试工具类 ### 3. 测试工具类
```typescript ```typescript
import { nativeWsTest } from '@/ws'; import { nativeWsTest } from "@/ws";
await nativeWsTest.testConnect(url, token, deviceId); await nativeWsTest.testConnect(url, token, deviceId);
``` ```
### 4. 可视化测试页面 ### 4. 可视化测试页面
- 文件:`pages/test-ws.uvue` - 文件:`pages/test-ws.uvue`
- 需要在 `pages.json` 中添加路由 - 需要在 `pages.json` 中添加路由
...@@ -122,11 +129,13 @@ await nativeWsTest.testConnect(url, token, deviceId); ...@@ -122,11 +129,13 @@ await nativeWsTest.testConnect(url, token, deviceId);
### 从 socket.io 迁移到原生 WebSocket ### 从 socket.io 迁移到原生 WebSocket
**之前(socket.io):** **之前(socket.io):**
- 使用特定的握手协议 - 使用特定的握手协议
- 连接路径:`/socket.io/` - 连接路径:`/socket.io/`
- 消息格式:socket.io 包装格式 - 消息格式:socket.io 包装格式
**现在(原生 WebSocket):** **现在(原生 WebSocket):**
- 标准 WebSocket 协议 - 标准 WebSocket 协议
- 连接路径:`/ws` 或 `/websocket` - 连接路径:`/ws` 或 `/websocket`
- 消息格式:纯 JSON 字符串 - 消息格式:纯 JSON 字符串
...@@ -138,6 +147,7 @@ ws://host:port/path?token=YOUR_TOKEN&deviceId=YOUR_DEVICE_ID ...@@ -138,6 +147,7 @@ ws://host:port/path?token=YOUR_TOKEN&deviceId=YOUR_DEVICE_ID
``` ```
示例: 示例:
``` ```
ws://192.168.1.237:8081/ws?token=abc123&deviceId=device001 ws://192.168.1.237:8081/ws?token=abc123&deviceId=device001
``` ```
...@@ -147,20 +157,20 @@ ws://192.168.1.237:8081/ws?token=abc123&deviceId=device001 ...@@ -147,20 +157,20 @@ ws://192.168.1.237:8081/ws?token=abc123&deviceId=device001
### 使用主 Ws 类(推荐) ### 使用主 Ws 类(推荐)
```typescript ```typescript
import ws from '@/ws'; import ws from "@/ws";
// 连接(自动登录) // 连接(自动登录)
await ws.connect(); await ws.connect();
// 发送消息 // 发送消息
await ws.send({ await ws.send({
command: 'message', command: "message",
data: { content: 'Hello' } data: { content: "Hello" },
}); });
// 监听消息 // 监听消息
ws.setOnMessage((data) => { ws.setOnMessage((data) => {
console.log('收到消息:', data); console.log("收到消息:", data);
}); });
// 关闭连接 // 关闭连接
...@@ -170,19 +180,15 @@ await ws.close(); ...@@ -170,19 +180,15 @@ await ws.close();
### 使用测试工具类 ### 使用测试工具类
```typescript ```typescript
import { nativeWsTest } from '@/ws'; import { nativeWsTest } from "@/ws";
// 连接 // 连接
await nativeWsTest.testConnect( await nativeWsTest.testConnect("ws://192.168.1.237:8081/ws", "your-token", "your-device-id");
'ws://192.168.1.237:8081/ws',
'your-token',
'your-device-id'
);
// 发送消息 // 发送消息
nativeWsTest.send({ nativeWsTest.send({
command: 'message', command: "message",
data: { content: 'Test' } data: { content: "Test" },
}); });
// 关闭 // 关闭
...@@ -199,14 +205,10 @@ export const SOCKET_SERVER: string = "ws://192.168.1.237:8080"; ...@@ -199,14 +205,10 @@ export const SOCKET_SERVER: string = "ws://192.168.1.237:8080";
export const wsConfig: WsConfig = { export const wsConfig: WsConfig = {
wsUrl: SOCKET_SERVER, wsUrl: SOCKET_SERVER,
loginUrl: `${HTTP_SERVER}/login` loginUrl: `${HTTP_SERVER}/login`,
}; };
export const WS_LOGIN_URLS: string[] = [ export const WS_LOGIN_URLS: string[] = [`${HTTP_SERVER}/login`, `${HTTP_SERVER}/api/login`, `${HTTP_SERVER}/ws/login`];
`${HTTP_SERVER}/login`,
`${HTTP_SERVER}/api/login`,
`${HTTP_SERVER}/ws/login`
];
``` ```
## 🐛 故障排除 ## 🐛 故障排除
...@@ -214,6 +216,7 @@ export const WS_LOGIN_URLS: string[] = [ ...@@ -214,6 +216,7 @@ export const WS_LOGIN_URLS: string[] = [
### 编译错误 ### 编译错误
如果遇到编译错误: 如果遇到编译错误:
1. 检查所有文件是否正确保存 1. 检查所有文件是否正确保存
2. 清理编译缓存 2. 清理编译缓存
3. 重新运行项目 3. 重新运行项目
...@@ -221,6 +224,7 @@ export const WS_LOGIN_URLS: string[] = [ ...@@ -221,6 +224,7 @@ export const WS_LOGIN_URLS: string[] = [
### 运行时错误 ### 运行时错误
如果遇到 `NoSuchMethodError` 或 `NoClassDefFoundError`: 如果遇到 `NoSuchMethodError` 或 `NoClassDefFoundError`:
1. **必须清理编译缓存**(见快速修复指南) 1. **必须清理编译缓存**(见快速修复指南)
2. 重新运行项目 2. 重新运行项目
3. 如果还不行,卸载应用重装 3. 如果还不行,卸载应用重装
...@@ -228,6 +232,7 @@ export const WS_LOGIN_URLS: string[] = [ ...@@ -228,6 +232,7 @@ export const WS_LOGIN_URLS: string[] = [
### 连接失败 ### 连接失败
如果 WebSocket 连接失败: 如果 WebSocket 连接失败:
1. 检查服务端是否运行 1. 检查服务端是否运行
2. 确认 IP 地址和端口正确 2. 确认 IP 地址和端口正确
3. 检查 token 和 deviceId 是否有效 3. 检查 token 和 deviceId 是否有效
...@@ -238,9 +243,10 @@ export const WS_LOGIN_URLS: string[] = [ ...@@ -238,9 +243,10 @@ export const WS_LOGIN_URLS: string[] = [
### 登录服务器连接失败 ### 登录服务器连接失败
如果看到 `Connection refused` 错误: 如果看到 `Connection refused` 错误:
1. **推荐:使用直接连接方式**(跳过登录) 1. **推荐:使用直接连接方式**(跳过登录)
```typescript ```typescript
import { quickTestDirectConnect } from '@/ws'; import { quickTestDirectConnect } from "@/ws";
// 修改 ws/direct-test.uts 配置 // 修改 ws/direct-test.uts 配置
await quickTestDirectConnect(); await quickTestDirectConnect();
``` ```
...@@ -303,6 +309,7 @@ ws/ ...@@ -303,6 +309,7 @@ ws/
## 📞 需要帮助? ## 📞 需要帮助?
如果遇到问题: 如果遇到问题:
1. 查看对应的文档 1. 查看对应的文档
2. 检查控制台日志 2. 检查控制台日志
3. 查看服务端日志 3. 查看服务端日志
......
# Vue3 微前端子应用模板
> 基于 qiankun + Vue3 + Vite + TypeScript 构建的微前端子应用模板
## 📋 目录
- [功能特性](#功能特性)
- [技术栈](#技术栈)
- [快速开始](#快速开始)
- [项目结构](#项目结构)
- [与基座联调](#与基座联调)
- [配置说明](#配置说明)
- [开发指南](#开发指南)
## ✨ 功能特性
- 🚀 **快速启动** - 使用 Vite 构建,HMR 响应迅速
- 🎯 **独立运行** - 支持独立开发和集成运行两种模式
- 🔧 **开箱即用** - 集成路由、状态管理、自动导入等功能
- 💡 **TypeScript** - 完整的类型支持,开发更安全
- 🎨 **现代化 UI** - 精心设计的用户界面和交互体验
- 🔌 **qiankun 集成** - 完整实现 qiankun 生命周期钩子
## 🛠️ 技术栈
- **Vue 3** - 渐进式 JavaScript 框架
- **TypeScript** - 类型安全的 JavaScript 超集
- **Vite** - 新一代前端构建工具
- **Vue Router** - 官方路由管理器
- **Pinia** - 新一代状态管理库
- **qiankun** - 微前端框架
- **vite-plugin-qiankun** - Vite 的 qiankun 插件
## 🚀 快速开始
### 安装依赖
```bash
pnpm install
```
### 启动开发服务器
```bash
pnpm dev
```
访问 `http://localhost:8081` 即可查看应用(独立运行模式)
### 构建生产版本
```bash
pnpm build
```
### 预览生产构建
```bash
pnpm preview
```
## 📁 项目结构
```
micro-app-template/
├── src/
│ ├── views/ # 页面组件
│ │ ├── Home.vue # 首页
│ │ ├── About.vue # 关于页
│ │ ├── User.vue # 用户管理
│ │ ├── Settings.vue # 系统设置
│ │ └── NotFound.vue # 404 页面
│ ├── router/ # 路由配置
│ │ └── index.ts # 路由定义
│ ├── App.vue # 根组件
│ ├── main.ts # 入口文件(包含 qiankun 生命周期)
│ └── style.css # 全局样式
├── index.html # HTML 模板
├── vite.config.ts # Vite 配置(qiankun 集成)
├── tsconfig.json # TypeScript 配置
├── package.json # 项目配置
└── README.md # 项目文档
```
## 🔗 与基座联调
### ⚠️ 重要提示
在启动前,请确保配置正确(已在本次更新中修复):
**子应用配置检查:**
- ✅ `vite.config.ts` - base 配置为 `http://localhost:8081/`
- ✅ `src/router/index.ts` - 导出 `createRouter` 函数
- ✅ `src/main.ts` - 动态创建路由实例
**基座配置检查:**
- ✅ `src/qiankun/apps.ts` - entry 配置为 `http://localhost:8081`
- ✅ `src/views/MicroApp.vue` - 包含 `<div id="subapp-container"></div>`
### 1. 启动子应用
```bash
cd apps/frontend-micro/micro-app-template
pnpm dev
```
子应用会在 `http://localhost:8081` 启动
**验证:**
- 访问 `http://localhost:8081` 应显示子应用
- 控制台显示 "独立运行模式"
### 2. 启动基座应用
```bash
cd apps/frontend-micro/scrm-base
pnpm dev
```
基座会在 `http://localhost:8080` 启动
**验证:**
- 控制台显示 "[qiankun] 微前端框架已启动"
### 3. 在基座中访问子应用
访问 `http://localhost:8080/subapp-vue`,基座会自动加载并挂载子应用
**预期结果:**
- 看到子应用内容(紫色渐变背景)
- 控制台显示生命周期日志
- 运行模式显示 "🔗 基座模式"
**详细测试步骤:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
## ⚙️ 配置说明
### 修改子应用端口
在 `vite.config.ts` 中修改 `PORT` 常量:
```typescript
const PORT = 8081; // 修改为你想要的端口
```
### 修改子应用名称
1. 在 `vite.config.ts` 中修改 `APP_NAME`:
```typescript
const APP_NAME = "your-app-name";
```
2. 在基座的 `src/micro-apps.ts` 中添加或修改对应配置:
```typescript
{
name: 'your-app-name',
entry: '//localhost:8081',
container: '#subapp-container',
activeRule: '/your-app-name',
props: {
routerBase: '/your-app-name',
},
}
```
### 路由配置
子应用路由会自动添加基座传递的 `routerBase` 前缀。在独立运行时,路由base为 `/`;在基座中运行时,路由base为基座配置的 `routerBase`(如 `/subapp-vue`)。
## 📝 开发指南
### 独立开发模式
子应用支持完全独立开发,无需启动基座:
```bash
pnpm dev
```
访问 `http://localhost:8081` 进行开发调试
### 集成开发模式
需要测试与基座的集成时:
1. 启动子应用:`pnpm dev`
2. 启动基座:在 scrm-base 目录执行 `pnpm dev`
3. 通过基座访问:`http://localhost:8080/subapp-vue`
### qiankun 生命周期说明
子应用实现了以下 qiankun 生命周期钩子:
- `bootstrap` - 应用初始化,只执行一次
- `mount` - 应用挂载,每次进入都会执行
- `unmount` - 应用卸载,每次离开都会执行
- `update` - 应用更新(可选),主应用下发新 props 时触发
### 环境判断
使用以下方式判断应用是否在 qiankun 环境中运行:
```typescript
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
if (qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log("在基座中运行");
} else {
console.log("独立运行");
}
```
## 🔍 常见问题
### 1. 子应用无法加载(白屏)
**原因:**
- 子应用未启动
- entry 地址配置错误
- 容器 ID 不存在
**解决:**
```bash
# 确认子应用运行
curl http://localhost:8081
# 检查基座配置
# scrm-base/src/qiankun/apps.ts
entry: 'http://localhost:8081' // ✅ 使用完整 URL
# 检查容器存在
# scrm-base/src/views/MicroApp.vue
<div id="subapp-container"></div> // ✅ 必须存在
```
### 2. CORS 错误
**控制台显示:**
```
Access to fetch at 'http://localhost:8081/' has been blocked by CORS policy
```
**解决:**
- 确认子应用 `vite.config.ts` 中 `cors: true`
- 确认 headers 配置正确
- 重启子应用服务
### 3. 路由跳转异常
**原因:**
- 路由 base 配置错误
- `routerBase` 未正确传递
**解决:**
```typescript
// ✅ 已修复:子应用动态创建路由
const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__ ? props.routerBase || "/subapp-vue" : "/";
const router = createRouter(routerBase);
```
### 4. 样式冲突
- qiankun 默认开启了样式隔离
- 建议使用 scoped 样式
- 可以在基座的 `start` 配置中调整样式隔离策略
### 5. 生命周期未触发
**原因:**
- 应用名称不一致
- 生命周期钩子未正确导出
**解决:**
```typescript
// vite.config.ts
qiankun("subapp-vue"); // 必须与基座配置一致
// main.ts
export async function bootstrap() {}
export async function mount(props) {}
export async function unmount(props) {}
```
**详细排查指南:** 请查看 [`INTEGRATION_GUIDE.md`](./INTEGRATION_GUIDE.md)
## 📄 License
MIT
## 🤝 贡献
欢迎提交 Issue 和 Pull Request!
<!doctype html> <!doctype html>
<html lang="zh-CN" style=" <html lang="zh-CN" style="--el-color-primary: #185efe">
--el-color-primary: #185efe">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
......
{
"$schema": "./component-manifest.schema.json",
"packageName": "@venus/common-ui-vue",
"packageRoot": "packages/common-ui/vue-ui",
"framework": "vue",
"notes": "第一阶段最小组件清单,仅覆盖当前已显式文档化的基础组件,用于后续 AI 组件映射试点。",
"components": [
{
"name": "button",
"exportName": "VButton",
"source": "src/components/VButton.vue",
"category": "action",
"description": "基于 Element Plus 的按钮包装组件,提供统一默认主按钮类型和 block 布局能力。",
"props": [
{
"name": "block",
"type": "boolean",
"description": "是否以整行宽度展示按钮。",
"default": "false"
},
{
"name": "circle",
"type": "boolean",
"description": "是否显示为圆形按钮。"
},
{
"name": "disabled",
"type": "boolean",
"description": "是否禁用按钮。"
},
{
"name": "loading",
"type": "boolean",
"description": "是否展示加载状态。"
},
{
"name": "plain",
"type": "boolean",
"description": "是否使用朴素按钮样式。"
},
{
"name": "round",
"type": "boolean",
"description": "是否显示为圆角按钮。"
},
{
"name": "size",
"type": "'default' | 'large' | 'small'",
"description": "按钮尺寸。"
},
{
"name": "type",
"type": "'default' | 'primary' | 'success' | 'warning' | 'danger' | 'info'",
"description": "按钮视觉类型,未显式指定时默认按 primary 处理。"
}
],
"events": [
{
"name": "click",
"description": "按钮点击事件。",
"payload": "MouseEvent"
}
],
"slots": [
{
"name": "default",
"description": "按钮文本或自定义内容。"
}
],
"figmaMapping": {
"keywords": ["button", "primary action", "secondary action", "cta"],
"nodeTypes": ["COMPONENT", "INSTANCE"],
"variantHints": ["primary", "danger", "loading", "disabled"]
},
"usageGuidance": {
"recommendedScenarios": ["表单提交操作", "卡片或弹窗主操作按钮", "需要整行按钮的移动端入口"],
"avoidScenarios": ["纯文本导航链接", "需要复杂前后缀插槽的按钮排版"],
"dependencies": ["element-plus"]
}
},
{
"name": "input",
"exportName": "VInput",
"source": "src/components/VInput.vue",
"category": "form",
"description": "基于 Element Plus 的输入框包装组件,提供统一外观和常用插槽透传。",
"props": [
{
"name": "block",
"type": "boolean",
"description": "是否按整行宽度展示输入框。",
"default": "false"
},
{
"name": "clearable",
"type": "boolean",
"description": "是否允许一键清空。"
},
{
"name": "disabled",
"type": "boolean",
"description": "是否禁用输入框。"
},
{
"name": "modelValue",
"type": "number | string",
"description": "输入框当前值。"
},
{
"name": "placeholder",
"type": "string",
"description": "占位提示文本。"
},
{
"name": "type",
"type": "string",
"description": "输入框类型,例如 text 或 password。"
}
],
"events": [
{
"name": "update:modelValue",
"description": "输入值变化事件。",
"payload": "number | string"
}
],
"slots": [
{
"name": "prepend",
"description": "输入框前置区域。"
},
{
"name": "append",
"description": "输入框后置区域。"
},
{
"name": "prefix",
"description": "输入框内部前缀内容。"
},
{
"name": "suffix",
"description": "输入框内部后缀内容。"
}
],
"figmaMapping": {
"keywords": ["input", "text field", "form input", "search input", "password field"],
"nodeTypes": ["COMPONENT", "FRAME", "INSTANCE"],
"variantHints": ["with prepend", "with suffix", "password", "disabled"]
},
"usageGuidance": {
"recommendedScenarios": ["表单基础输入项", "登录页账号密码输入", "需要前后缀内容的输入场景"],
"avoidScenarios": ["富文本输入", "多行文本编辑", "复杂搜索工具条的完整封装"],
"dependencies": ["element-plus"]
}
}
]
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://venus.local/contracts/ai/component-manifest.schema.json",
"type": "object",
"required": ["packageName", "packageRoot", "framework", "components"],
"properties": {
"packageName": { "type": "string" },
"packageRoot": { "type": "string" },
"framework": { "type": "string", "enum": ["react", "shared", "vue"] },
"notes": { "type": "string" },
"components": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/component" }
}
},
"additionalProperties": false,
"$defs": {
"prop": {
"type": "object",
"required": ["name", "type", "description"],
"properties": {
"name": { "type": "string" },
"type": { "type": "string" },
"description": { "type": "string" },
"required": { "type": "boolean" },
"default": { "type": "string" }
},
"additionalProperties": false
},
"event": {
"type": "object",
"required": ["name", "description"],
"properties": {
"name": { "type": "string" },
"description": { "type": "string" },
"payload": { "type": "string" }
},
"additionalProperties": false
},
"slot": {
"type": "object",
"required": ["name", "description"],
"properties": {
"name": { "type": "string" },
"description": { "type": "string" }
},
"additionalProperties": false
},
"figmaMapping": {
"type": "object",
"required": ["keywords", "nodeTypes"],
"properties": {
"keywords": {
"type": "array",
"items": { "type": "string" }
},
"nodeTypes": {
"type": "array",
"items": { "type": "string" }
},
"variantHints": {
"type": "array",
"items": { "type": "string" }
}
},
"additionalProperties": false
},
"usageGuidance": {
"type": "object",
"required": ["recommendedScenarios"],
"properties": {
"recommendedScenarios": {
"type": "array",
"items": { "type": "string" }
},
"avoidScenarios": {
"type": "array",
"items": { "type": "string" }
},
"dependencies": {
"type": "array",
"items": { "type": "string" }
}
},
"additionalProperties": false
},
"component": {
"type": "object",
"required": ["name", "exportName", "source", "category", "description", "figmaMapping", "usageGuidance"],
"properties": {
"name": { "type": "string" },
"exportName": { "type": "string" },
"source": { "type": "string" },
"category": { "type": "string" },
"description": { "type": "string" },
"props": {
"type": "array",
"items": { "$ref": "#/$defs/prop" }
},
"events": {
"type": "array",
"items": { "$ref": "#/$defs/event" }
},
"slots": {
"type": "array",
"items": { "$ref": "#/$defs/slot" }
},
"figmaMapping": { "$ref": "#/$defs/figmaMapping" },
"usageGuidance": { "$ref": "#/$defs/usageGuidance" }
},
"additionalProperties": false
}
}
}
{
"$schema": "../page-schema.schema.json",
"pageId": "user-management-list",
"title": "User Management",
"intent": "list",
"source": {
"kind": "manual",
"reference": "Standard admin list page pilot"
},
"route": {
"path": "/users",
"name": "UserManagementList",
"requiresAuth": true,
"menuTitle": "Users"
},
"layout": {
"shell": "list",
"responsive": true,
"columns": 1
},
"sections": [
{
"id": "filters",
"name": "Filters",
"purpose": "Collect search and filter criteria before querying the table.",
"blocks": [
{
"id": "filter-form",
"kind": "form",
"title": "Search Users",
"componentHint": "FilterToolbar",
"fields": [
{
"id": "keyword",
"label": "Keyword",
"type": "text",
"componentHint": "VInput"
},
{
"id": "status",
"label": "Status",
"type": "select",
"componentHint": "StatusSelect"
}
],
"actions": [
{
"id": "search",
"label": "Search",
"kind": "submit",
"componentHint": "VButton"
},
{
"id": "reset",
"label": "Reset",
"kind": "toggle",
"componentHint": "VButton"
}
]
}
]
},
{
"id": "results",
"name": "Results",
"purpose": "Display queried user records and row-level operations.",
"blocks": [
{
"id": "toolbar-actions",
"kind": "actions",
"title": "Page Actions",
"actions": [
{
"id": "create-user",
"label": "Create User",
"kind": "dialog",
"componentHint": "VButton"
}
]
},
{
"id": "user-table",
"kind": "table",
"title": "User Table",
"description": "Table with pagination, status badge and row actions.",
"componentHint": "DataTable",
"actions": [
{
"id": "view-user",
"label": "View",
"kind": "navigate",
"componentHint": "VButton"
},
{
"id": "edit-user",
"label": "Edit",
"kind": "dialog",
"componentHint": "VButton"
}
]
}
]
}
],
"dataRequirements": [
{
"id": "users-query",
"kind": "query",
"name": "fetchUsers",
"description": "Fetch paginated user list with keyword and status filters."
},
{
"id": "create-user-mutation",
"kind": "mutation",
"name": "createUser",
"description": "Create a user from the toolbar dialog."
}
],
"notes": "Pilot page schema for list-page generation. Blocks are intentionally simple and can be extended later."
}
{
"projectName": "@venus/venus-agentic-base",
"projectRoot": "D:/work/venus/apps/web/venus-agentic/venus-agentic-base",
"framework": "micro-frontend",
"appType": "micro-app",
"workspace": {
"inWorkspace": true,
"workspaceRoot": "D:/work/venus",
"packageName": "@venus/venus-agentic-base",
"packageManager": "pnpm"
},
"directories": {
"srcDir": "src",
"componentDirs": ["src/components"],
"pageDirs": ["src/views"],
"routeFiles": ["src/router/index.ts"],
"storeFiles": [
"src/stores/app.ts",
"src/stores/index.ts",
"src/stores/menu.ts",
"src/stores/permission.ts",
"src/stores/user.ts"
],
"styleDirs": ["src/styles"]
},
"routing": {
"solution": "vue-router",
"menuCoupled": true,
"requiresRegistration": true
},
"stateManagement": {
"solution": "pinia",
"persistence": false
},
"uiStack": {
"componentPackages": ["@venus/common-ui-vue", "element-plus"],
"primaryLibrary": "@venus/common-ui-vue",
"tokenSource": "venus-component-library"
},
"qualityGates": {
"lint": "pnpm lint",
"typecheck": "pnpm run check:type",
"templateContract": "pnpm run check:template-contract",
"reviewTrigger": "pnpm run review:trigger",
"fitness": "pnpm run check:fitness -- --tier fast"
},
"constraints": [
"changes must respect workspace-level quality gates",
"route and shell integration must remain qiankun-compatible",
"prefer existing @venus/common-ui-vue components before introducing raw UI markup",
"new pages should include route registration planning",
"state additions should align with the current pinia store layout"
],
"notes": "Generated by the project-intelligence pilot reader. Refine fields as more project patterns are covered."
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://venus.local/contracts/ai/page-schema.schema.json",
"type": "object",
"required": ["pageId", "title", "source", "layout", "sections"],
"properties": {
"pageId": { "type": "string" },
"title": { "type": "string" },
"intent": {
"type": "string",
"enum": ["dashboard", "detail", "form", "list", "settings", "unknown"]
},
"source": { "$ref": "#/$defs/source" },
"route": { "$ref": "#/$defs/route" },
"layout": { "$ref": "#/$defs/layout" },
"sections": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/section" }
},
"dataRequirements": {
"type": "array",
"items": { "$ref": "#/$defs/dataRequirement" }
},
"notes": { "type": "string" }
},
"additionalProperties": false,
"$defs": {
"source": {
"type": "object",
"required": ["kind"],
"properties": {
"kind": {
"type": "string",
"enum": ["figma-frame", "manual", "mixed", "requirement-text"]
},
"reference": { "type": "string" },
"frameName": { "type": "string" }
},
"additionalProperties": false
},
"route": {
"type": "object",
"properties": {
"path": { "type": "string" },
"name": { "type": "string" },
"requiresAuth": { "type": "boolean" },
"menuTitle": { "type": "string" }
},
"additionalProperties": false
},
"layout": {
"type": "object",
"required": ["shell"],
"properties": {
"shell": {
"type": "string",
"enum": ["blank", "dashboard", "detail", "form", "list", "workspace"]
},
"responsive": { "type": "boolean" },
"columns": { "type": "integer", "minimum": 1 }
},
"additionalProperties": false
},
"action": {
"type": "object",
"required": ["id", "label", "kind"],
"properties": {
"id": { "type": "string" },
"label": { "type": "string" },
"kind": {
"type": "string",
"enum": ["dialog", "navigate", "request", "submit", "toggle"]
},
"componentHint": { "type": "string" }
},
"additionalProperties": false
},
"field": {
"type": "object",
"required": ["id", "label", "type"],
"properties": {
"id": { "type": "string" },
"label": { "type": "string" },
"type": {
"type": "string",
"enum": ["date", "number", "select", "switch", "text", "textarea"]
},
"required": { "type": "boolean" },
"componentHint": { "type": "string" }
},
"additionalProperties": false
},
"block": {
"type": "object",
"required": ["id", "kind"],
"properties": {
"id": { "type": "string" },
"kind": {
"type": "string",
"enum": [
"actions",
"card",
"chart",
"container",
"description",
"form",
"hero",
"list",
"stats",
"table",
"text"
]
},
"title": { "type": "string" },
"description": { "type": "string" },
"componentHint": { "type": "string" },
"figmaNodeId": { "type": "string" },
"fields": {
"type": "array",
"items": { "$ref": "#/$defs/field" }
},
"actions": {
"type": "array",
"items": { "$ref": "#/$defs/action" }
},
"children": {
"type": "array",
"items": { "$ref": "#/$defs/block" }
},
"tokenRefs": {
"type": "array",
"items": { "type": "string" }
}
},
"additionalProperties": false
},
"section": {
"type": "object",
"required": ["id", "name", "blocks"],
"properties": {
"id": { "type": "string" },
"name": { "type": "string" },
"purpose": { "type": "string" },
"blocks": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#/$defs/block" }
}
},
"additionalProperties": false
},
"dataRequirement": {
"type": "object",
"required": ["id", "kind", "name"],
"properties": {
"id": { "type": "string" },
"kind": {
"type": "string",
"enum": ["mutation", "query", "static"]
},
"name": { "type": "string" },
"description": { "type": "string" }
},
"additionalProperties": false
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://venus.local/contracts/ai/project-context.schema.json",
"type": "object",
"required": ["projectName", "projectRoot", "workspace", "framework", "directories", "qualityGates"],
"properties": {
"projectName": { "type": "string" },
"projectRoot": { "type": "string" },
"framework": {
"type": "string",
"enum": ["micro-frontend", "react", "shared", "uniappX", "unknown", "vue"]
},
"appType": {
"type": "string",
"enum": ["admin", "library", "micro-app", "template-output", "tooling", "unknown"]
},
"workspace": { "$ref": "#/$defs/workspace" },
"directories": { "$ref": "#/$defs/directories" },
"routing": { "$ref": "#/$defs/routing" },
"stateManagement": { "$ref": "#/$defs/stateManagement" },
"uiStack": { "$ref": "#/$defs/uiStack" },
"qualityGates": { "$ref": "#/$defs/qualityGates" },
"constraints": {
"type": "array",
"items": { "type": "string" }
},
"notes": { "type": "string" }
},
"additionalProperties": false,
"$defs": {
"workspace": {
"type": "object",
"required": ["inWorkspace"],
"properties": {
"inWorkspace": { "type": "boolean" },
"workspaceRoot": { "type": "string" },
"packageName": { "type": "string" },
"packageManager": {
"type": "string",
"enum": ["npm", "pnpm", "unknown", "yarn"]
}
},
"additionalProperties": false
},
"directories": {
"type": "object",
"required": ["srcDir"],
"properties": {
"srcDir": { "type": "string" },
"componentDirs": {
"type": "array",
"items": { "type": "string" }
},
"pageDirs": {
"type": "array",
"items": { "type": "string" }
},
"routeFiles": {
"type": "array",
"items": { "type": "string" }
},
"storeFiles": {
"type": "array",
"items": { "type": "string" }
},
"styleDirs": {
"type": "array",
"items": { "type": "string" }
}
},
"additionalProperties": false
},
"routing": {
"type": "object",
"properties": {
"solution": {
"type": "string",
"enum": ["file-based", "manual", "react-router", "unknown", "vue-router"]
},
"menuCoupled": { "type": "boolean" },
"requiresRegistration": { "type": "boolean" }
},
"additionalProperties": false
},
"stateManagement": {
"type": "object",
"properties": {
"solution": {
"type": "string",
"enum": ["none", "pinia", "redux", "unknown", "zustand"]
},
"persistence": { "type": "boolean" }
},
"additionalProperties": false
},
"uiStack": {
"type": "object",
"properties": {
"componentPackages": {
"type": "array",
"items": { "type": "string" }
},
"primaryLibrary": { "type": "string" },
"tokenSource": { "type": "string" }
},
"additionalProperties": false
},
"qualityGates": {
"type": "object",
"required": ["lint"],
"properties": {
"lint": { "type": "string" },
"typecheck": { "type": "string" },
"templateContract": { "type": "string" },
"reviewTrigger": { "type": "string" },
"fitness": { "type": "string" }
},
"additionalProperties": false
}
}
}
{
"$schema": "./template-contract.schema.json",
"template": "react",
"templateRoot": "packages/cli/templates/react",
"baseFiles": ["package.json", "index.html", "tsconfig.json", "vite.config.ts", "src/App.tsx", "src/main.tsx"],
"features": {
"router": {
"featurePath": "optional/router",
"overlayFiles": ["_package.merge.json", "src/main.tsx"],
"mergedPackageRequirements": {
"dependencies": ["react-router-dom"]
}
},
"store": {
"featurePath": "optional/store",
"overlayFiles": ["_package.merge.json", "src/components/Counter.tsx", "src/store/counter.ts"],
"mergedPackageRequirements": {
"dependencies": ["zustand"]
}
},
"ui": {
"variants": {
"antd": {
"featurePath": "optional/ui/antd",
"overlayFiles": ["_package.merge.json", "src/ui.tsx"],
"mergedPackageRequirements": {
"dependencies": ["antd"]
}
}
}
},
"eslint": {
"featurePath": "optional/eslint",
"overlayFiles": ["_package.merge.json", "eslint.config.mjs"],
"mergedPackageRequirements": {
"devDependencies": ["eslint", "@venus/eslint-config"],
"scripts": ["lint", "lint:fix"]
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://venus.local/contracts/template-contract.schema.json",
"type": "object",
"required": ["template", "templateRoot", "baseFiles", "features"],
"properties": {
"template": { "type": "string" },
"templateRoot": { "type": "string" },
"baseFiles": {
"type": "array",
"items": { "type": "string" }
},
"features": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/feature"
}
}
},
"$defs": {
"packageRequirements": {
"type": "object",
"properties": {
"dependencies": { "type": "array", "items": { "type": "string" } },
"devDependencies": { "type": "array", "items": { "type": "string" } },
"scripts": { "type": "array", "items": { "type": "string" } }
},
"additionalProperties": false
},
"feature": {
"type": "object",
"properties": {
"featurePath": { "type": "string" },
"overlayFiles": { "type": "array", "items": { "type": "string" } },
"mergedPackageRequirements": { "$ref": "#/$defs/packageRequirements" },
"variants": {
"type": "object",
"additionalProperties": {
"type": "object",
"required": ["featurePath", "overlayFiles"],
"properties": {
"featurePath": { "type": "string" },
"overlayFiles": { "type": "array", "items": { "type": "string" } },
"mergedPackageRequirements": { "$ref": "#/$defs/packageRequirements" }
},
"additionalProperties": false
}
}
},
"additionalProperties": false,
"anyOf": [{ "required": ["featurePath", "overlayFiles"] }, { "required": ["variants"] }]
}
}
}
{
"$schema": "./template-contract.schema.json",
"template": "vue",
"templateRoot": "packages/cli/templates/vue",
"baseFiles": [
"package.json",
"index.html",
"tsconfig.json",
"tsconfig.node.json",
"vite.config.ts",
"src/App.vue",
"src/main.ts"
],
"features": {
"axios": {
"featurePath": "optional/axios",
"overlayFiles": ["_package.merge.json"],
"mergedPackageRequirements": {
"dependencies": ["axios"]
}
},
"router": {
"featurePath": "optional/router",
"overlayFiles": ["_package.merge.json", "src/router.ts"],
"mergedPackageRequirements": {
"dependencies": ["vue-router"]
}
},
"store": {
"featurePath": "optional/store",
"overlayFiles": ["_package.merge.json", "src/store/index.ts"],
"mergedPackageRequirements": {
"dependencies": ["pinia"]
}
},
"ui": {
"variants": {
"element-plus": {
"featurePath": "optional/ui/element-plus",
"overlayFiles": ["_package.merge.json", "src/ui.ts"],
"mergedPackageRequirements": {
"dependencies": ["element-plus"]
}
}
}
},
"eslint": {
"featurePath": "optional/eslint",
"overlayFiles": ["_package.merge.json", "eslint.config.mjs"],
"mergedPackageRequirements": {
"devDependencies": ["eslint", "@venus/eslint-config"],
"scripts": ["lint", "lint:fix"]
}
}
}
}
...@@ -47,7 +47,7 @@ export default defineConfig({ ...@@ -47,7 +47,7 @@ export default defineConfig({
{ {
text: "基础", text: "基础",
items: [ items: [
{ text: "目录结构", link: "/guide/directory-structure" }, { text: "目录结构", link: "/guide/structure" },
{ text: "构建说明", link: "/guide/buildREADME" }, { text: "构建说明", link: "/guide/buildREADME" },
{ text: "路由和菜单", link: "/guide/router-menu" }, { text: "路由和菜单", link: "/guide/router-menu" },
{ text: "权限管理", link: "/guide/permission" }, { text: "权限管理", link: "/guide/permission" },
...@@ -68,18 +68,17 @@ export default defineConfig({ ...@@ -68,18 +68,17 @@ export default defineConfig({
{ {
text: "开始", text: "开始",
items: [ items: [
{ text: "简介", link: "/guide/introduction" }, { text: "简介", link: "/micro/introduction" },
{ text: "快速开始", link: "/guide/quick-start" }, { text: "快速开始", link: "/micro/docs/QUICK_START" },
{ text: "项目配置", link: "/guide/configuration" }, { text: "qiankun 集成", link: "/micro/docs/qiankun" },
], ],
}, },
{ {
text: "基础", text: "运行与配置",
items: [ items: [
{ text: "目录结构", link: "/guide/directory-structure" }, { text: "系统公共配置", link: "/micro/commonConfig" },
{ text: "路由和菜单", link: "/guide/router-menu" }, { text: "项目结构", link: "/micro/docs/PROJECT_STRUCTURE" },
{ text: "权限管理", link: "/guide/permission" }, { text: "登录系统", link: "/micro/docs/登录系统使用说明" },
{ text: "状态管理", link: "/guide/state-management" },
], ],
}, },
], ],
......
# Venus 文档 # 文档维护说明
欢迎使用 Venus 文档! 本页面向维护者,说明 `docs/` 目录的职责划分、站点运行方式和整理约定。
这是基于 VitePress 构建的文档站点,包含了 Venus 的完整使用指南、API 参考和最佳实践。 如果你是文档读者,请直接从 `docs/index.md` 或 VitePress 首页进入;`README.md` 不再承担读者首页职责。
## 快速开始 ## 本地运行
```bash ```bash
# 安装依赖
pnpm install pnpm install
pnpm --dir docs dev
pnpm --dir docs build
pnpm --dir docs preview
```
# 启动开发服务器 ## 职责边界
pnpm dev
# 构建文档
pnpm build
# 预览构建结果 - `docs/index.md`:面向读者的站点首页,负责导航入口和产品介绍。
pnpm preview - `docs/README.md`:面向维护者的说明页,负责目录职责、维护流程和约定。
``` - `docs/guide/`:通用使用指南,按“介绍 / 结构 / 工作机制 / 功能专题”拆分。
- `docs/micro/`:微前端专题文档,`introduction.md` 作为稳定入口页,`docs/*.md` 收纳历史专题与排障记录。
- `docs/.vitepress/`:站点导航、侧边栏、主题配置。
- `docs/exec-plans/`、`docs/fitness/`、`docs/issues/ai-failures/`:治理证据,不与读者教程混写。
## 文档结构 ## 当前目录建议
``` ```text
docs/ docs/
├── guide/ # 用户指南 |-- .vitepress/ # VitePress 站点配置
│ ├── quick-start.md # 快速开始 |-- guide/ # 面向读者的通用指南
│ ├── introduction.md # 项目介绍 |-- micro/ # 微前端专题入口与历史文档
│ ├── structure.md # 项目结构 |-- architecture/ # 架构说明
│ ├── router-menu.md # 路由菜单 |-- exec-plans/ # 执行计划
│ ├── permission.md # 权限管理 |-- fitness/ # 质量维度与指标
│ ├── cli-usage.md # CLI 使用指南 ⭐ 新增 |-- issues/ai-failures/ # AI 失败样例与回流
│ ├── configuration.md # 配置指南 ⭐ 新增 |-- index.md # 站点首页
│ ├── monorepo.md # Monorepo 架构 ⭐ 新增 `-- README.md # 维护说明
│ ├── dependency.md # 依赖管理 ⭐ 新增
│ └── troubleshooting.md # 故障排查 ⭐ 新增
├── micro/ # 微前端文档
│ ├── intruduction.md
│ └── docs/
├── index.md # 首页
├── changelog.md # 更新日志
└── README.md # 文档说明
``` ```
## 核心文档 ## 维护约定
### 用户指南
- **[快速开始](./guide/quick-start.md)** - 快速上手 Venus 项目
- **[项目介绍](./guide/introduction.md)** - 了解 Venus 的特性和架构
- **[项目结构](./guide/structure.md)** - 理解项目目录结构
- **[CLI 使用指南](./guide/cli-usage.md)** ⭐ - 完整的 CLI 工具使用说明
- **[配置指南](./guide/configuration.md)** ⭐ - 项目配置详解和最佳实践
- **[Monorepo 架构](./guide/monorepo.md)** ⭐ - Monorepo 工作原理和实践
- **[依赖管理](./guide/dependency.md)** ⭐ - 依赖管理和优化
- **[故障排查](./guide/troubleshooting.md)** ⭐ - 常见问题解决方案
### 功能文档
- **[路由和菜单](./guide/router-menu.md)** - 路由配置和菜单管理
- **[权限管理](./guide/permission.md)** - 权限系统和访问控制
## 快速导航
### 新手入门
1. [快速开始](./guide/quick-start.md) - 环境准备和项目创建
2. [项目介绍](./guide/introduction.md) - 了解 Venus 的核心价值
3. [CLI 使用指南](./guide/cli-usage.md) - 掌握 CLI 工具的基本用法
### 进阶使用
1. [配置指南](./guide/configuration.md) - 深度定制项目配置
2. [Monorepo 架构](./guide/monorepo.md) - 理解 monorepo 工作机制
3. [依赖管理](./guide/dependency.md) - 优化依赖管理和性能
### 问题解决
1. [故障排查](./guide/troubleshooting.md) - 解决常见开发问题
2. [CLI 使用指南](./guide/cli-usage.md) - 诊断和修复工具使用
## 贡献文档
如果你发现文档有任何问题或想要改进文档,欢迎提交 Pull Request。 - 修改导航时,同时检查 `docs/.vitepress/config.ts` 中的 `nav` 和 `sidebar`,避免正文已改、入口仍指向旧链接。
- 新增专题时,优先补对应入口页,不要让读者直接面对散落的历史文档。
- 发生职责调整时,先收敛到单一入口页,再删除或降级历史副本,避免出现双入口。
- 对人的说明文档保持中文;命令、路径、frontmatter、JSON 字段保持原样,避免影响自动化。
- 微前端旧拼写页 `docs/micro/intruduction.md` 仅保留兼容跳转说明,不再承载正式内容。
### 文档编写规范 ## 常见维护动作
1. 使用 Markdown 格式 1. 新增页面后,补充导航、侧边栏和入口页链接。
2. 代码示例使用对应的语言标识 2. 删除或改名页面前,先全仓搜索引用,确认是否需要兼容占位页。
3. 保持文档结构清晰 3. 涉及信息架构调整时,在 `docs/exec-plans/` 中补执行计划,记录职责变化原因。
4. 添加必要的说明和注释 4. 提交前至少检查最近改动页面的预览和链接是否可访问。
## 相关链接 ## 参考链接
- [Venus Admin GitHub](https://github.com/venusjs/vue-venus-admin)
- [VitePress 官方文档](https://vitepress.dev) - [VitePress 官方文档](https://vitepress.dev)
- [仓库协作约定](../AGENTS.md)
# Venus 架构说明
## 目标
Venus 是一个基于 pnpm + Turbo 的 monorepo,在同一个受治理的工作区中统一承载应用模板、共享工具链、工作区策略和文档。
## 设计目标
- 将工作区级标准收敛到 `internal/` 下的共享包中。
- 通过 `packages/cli/templates/` 保持应用脚手架生成结果可预测、可重复。
- 让生成后的应用与共享 contract、校验逻辑保持一致。
- 让治理资产尽量靠近其所保护的代码。
## 核心层次
- 体验层:`apps/`
- 交付层:`packages/cli/`
- 策略层:`internal/`
- 自动化层:`scripts/`、`tools/fitness/`
- 治理层:`contracts/`、`docs/fitness/`、`docs/issues/`、`docs/exec-plans/`
## 治理边界
- 模板能力会被有意定义两次:一份面向人的说明,一份面向机器的 contract。
- 根级工作区配置是高风险边界,必须保持可审查、可解释。
- 共享 lint 和 tsconfig 包是整个 monorepo 的策略边界。
## AI-First 工程原则
- 规则优先:从 `AGENTS.md` 和仓库文档开始。
- 契约优先:行为声明和实现必须同步修改。
- 证据优先:高风险改动必须补充验证输出。
- 棘轮优先:先阻止质量继续恶化,再逐步清理历史债务。
# AI 设计稿到代码架构
## 目标
本专题定义 `venus` 如何从“受治理的前端 monorepo”继续演进为“面向 AI 的设计稿到代码工程系统”。
我们要解决的不是单次生成 demo,而是让 AI 能在以下两类场景中稳定工作:
- 新项目或新模块:根据 Figma 设计稿、页面描述和技术栈约束生成页面、组件、路由和基础样式。
- 老项目需求:先理解现有项目结构、依赖、组件库和编码习惯,再做增量补页、改页和 UI 替换。
## 核心结论
- `Figma -> 代码` 不是一步生成,而是一条多阶段管线。
- AI 是否可用,关键不在模型本身,而在 `venus` 是否提供了足够清晰的组件语义、项目上下文和验证回路。
- 当前 `venus` 最大短板不是 CLI,而是组件库基础、组件描述层和项目理解层不足。
## 当前现状
从仓库现状看:
- 已有治理骨架:`AGENTS.md`、`contracts/`、`review-trigger`、`fitness`、`smart-check`
- 已有模板能力:`packages/cli/templates/react`、`packages/cli/templates/vue`
- 已有少量组件基础:`packages/common-ui/vue-ui`
- 缺少统一 design tokens 包
- 缺少组件机器描述(props、插槽、适用场景、Figma 映射)
- 缺少项目上下文抽取层
- 缺少 Figma 解析与页面 schema 层
这意味着当前仓库适合先建设“AI 可消费上下文”,而不是直接追求端到端代码生成。
## 目标能力分层
建议将目标能力拆为三层,并按难度逐步推进:
### L1:设计还原
- 从 Figma 页面或 Frame 生成静态页面骨架
- 支持布局、文本、图片、基础组件占位
- 适合新页面、静态展示页、后台标准布局页
### L2:工程落地
- 根据 `venus` 模板、组件库和页面模板生成可运行代码
- 输出页面、组件、路由、状态和基础样式
- 适合新项目初始化、标准 CRUD 页面、后台模块生成
### L3:存量项目改造
- AI 在生成前先理解现有项目
- 根据现有路由、菜单、依赖、组件习惯做增量 patch
- 适合老项目新增需求、局部 UI 改版、标准模块补齐
## 总体架构
### 1. 设计系统层
这是 AI 可稳定生成 UI 的前提。
需要建设:
- `packages/components/` 或统一组件交付包
- `packages/design-tokens/`
- 组件元数据清单
- 页面模板清单
组件元数据至少要回答这些问题:
- 组件叫什么
- 面向什么场景
- 有哪些 props / slots / events
- 推荐和禁止的组合方式
- 对应哪些 Figma 节点和设计语义
没有这层,AI 只能生成“像页面的代码”,不能生成“符合 venus 规范的 UI”。
### 2. 项目理解层
这是老项目代码生成的关键。
AI 在写代码前,需要先产出一个“项目上下文画像”,至少包括:
- 项目框架:React / Vue / uniappX / 微前端
- 路由组织方式
- 状态管理方式
- 是否已有统一 UI 组件
- 已安装依赖与工作区约束
- 代码风格、目录结构和命名习惯
- 生成行为是否需要修改菜单、路由、权限、国际化
建议未来在 `packages/ai/project-intelligence/` 中落这一层。
### 3. Figma 解析层
Figma 输入不能直接映射最终代码,必须先抽成内部 schema。
推荐流程:
1. 读取 Figma 节点树、样式、组件引用和设计 token
2. 转成 `venus` 内部页面 schema
3. 将页面 schema 映射到 `venus` 组件树
4. 再进入代码生成
中间 schema 至少需要表达:
- 页面结构
- 区块层次
- 布局约束
- 文本语义
- 交互意图
- 组件候选
- token 引用
### 4. 代码生成层
建议拆成四段:
- planner:先产出生成计划和影响范围,不直接写文件
- mapper:把设计节点映射为 `venus` 组件和页面模板
- generator:生成新增文件
- patcher:对老项目进行最小范围修改
这层的目标不是“自由生成”,而是“尽量复用模板、组件和 contract”。
### 5. 验证治理层
AI 生成完成后,必须走统一验证链,而不是直接把结果当成完成。
当前已经存在的主链路可以直接复用:
1. `pnpm lint`
2. `pnpm run check:type`
3. `pnpm run check:template-contract`
4. `pnpm run review:trigger`
5. `pnpm run check:file-budget`
6. `pnpm run check:fitness -- --tier fast`
后续如果新增 AI 生成专属 contract,也应接入这条链。
## 推荐仓库落点
### 文档
- `docs/architecture/ai-design-to-code.md`
- `docs/exec-plans/*-ai-design-to-code-roadmap.md`
### 契约
- `contracts/ai/component-manifest.schema.json`
- `contracts/ai/page-schema.schema.json`
- `contracts/ai/project-context.schema.json`
### 代码包
- `packages/ai/project-intelligence/`
- `packages/ai/figma-ingest/`
- `packages/ai/design-mapper/`
- `packages/ai/codegen/`
- `packages/ai/patcher/`
### 组件和描述层
- `packages/common-ui/` 的组件补强
- `packages/design-tokens/`
- `contracts/ai/*.manifest.json`
## 分阶段路线
### 阶段 1:先补 AI 可消费上下文
目标:
- 明确组件库现状
- 建立组件 manifest schema
- 为现有组件补最小机器描述
- 定义项目上下文 schema
交付重点:
- 组件 manifest contract
- 当前组件库的最小 manifest
- 第一批 design tokens 结构
- 项目上下文抽取计划
### 阶段 2:打通新页面生成
目标:
- 基于页面描述或 Figma Frame 生成静态页/标准业务页
- 优先新增文件,不优先修改复杂存量文件
### 阶段 3:打通工程接入
目标:
- 自动接入路由、菜单、页面模板、基础状态和样式
- 让生成结果更接近真实项目可提交代码
### 阶段 4:支持老项目增量改造
目标:
- 先理解现有代码,再最小范围 patch
- 支持“新增需求”而不是仅支持“从零生成”
## 非目标
当前阶段不把以下内容当成首要目标:
- 一次性构建完整低代码平台
- 直接从复杂业务 Figma 稿一键生成全量业务逻辑
- 在没有组件语义层的前提下强行生成最终可交付页面
- 用 prompt 记忆替代 contract、schema 和治理证据
## 成功标准
当以下条件成立时,说明 `venus` 真正具备了 AI 设计稿到代码的工程基础:
- AI 能读取统一组件 manifest,而不是靠猜组件
- AI 能知道当前项目该用什么技术栈和目录结构
- AI 生成先经过 planner,再进入文件写入
- AI 生成结果能走统一 lint/type/contract/review 流程
- 新项目生成和老项目 patch 使用同一套项目理解与组件映射模型
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
## v0.1.0 (2026-05-26) ## v0.1.0 (2026-05-26)
### ✨ 新增功能 ### ✨ 新增功能
- **CLI 工具增强**: - **CLI 工具增强**:
- 新增项目诊断命令 (`venus diagnose`) - 新增项目诊断命令 (`venus diagnose`)
- 新增项目修复命令 (`venus fix`) - 新增项目修复命令 (`venus fix`)
...@@ -15,6 +16,7 @@ ...@@ -15,6 +16,7 @@
- 完善了 catalog: 依赖处理逻辑 - 完善了 catalog: 依赖处理逻辑
### 📝 文档完善 ### 📝 文档完善
- **主 README 文档**: - **主 README 文档**:
- 填充了项目简介和核心价值 - 填充了项目简介和核心价值
- 添加了升级提示和版本升级指南 - 添加了升级提示和版本升级指南
...@@ -27,18 +29,21 @@ ...@@ -27,18 +29,21 @@
- 故障排查指南 (`docs/guide/troubleshooting.md`) - 故障排查指南 (`docs/guide/troubleshooting.md`)
### 🐛 问题修复 ### 🐛 问题修复
- 修复了 CLI 在子项目中执行 `pnpm install` 导致依赖重复下载的问题 - 修复了 CLI 在子项目中执行 `pnpm install` 导致依赖重复下载的问题
- 修复了 catalog: 依赖软链接建立失败的问题 - 修复了 catalog: 依赖软链接建立失败的问题
- 修复了文档链接无效的问题 - 修复了文档链接无效的问题
- 修复了版本号不一致的问题 - 修复了版本号不一致的问题
### 🔧 工具链优化 ### 🔧 工具链优化
- 优化了 pnpm workspace 配置 - 优化了 pnpm workspace 配置
- 改进了 Turbo 构建配置 - 改进了 Turbo 构建配置
- 完善了 ESLint 和 Prettier 配置 - 完善了 ESLint 和 Prettier 配置
- 添加了依赖分析工具 - 添加了依赖分析工具
### 📚 文档优化 ### 📚 文档优化
- 统一了文档格式和风格 - 统一了文档格式和风格
- 添加了详细的代码示例 - 添加了详细的代码示例
- 补充了最佳实践指南 - 补充了最佳实践指南
......
# 第二阶段 AI 治理执行计划
## 目标
- 修复 `codeql.yml` 的 YAML 语法问题,消除其对全量 lint 的直接污染。
- 为仓库补上 file budget / hotspot guard,建立“历史热点只许收缩、不许继续膨胀”的约束。
- 把 React / Vue 模板 ESLint 可选能力缺失问题沉淀为第一条真实失败样例记录。
## 范围
- `.github/workflows/codeql.yml`
- `.prettierignore`
- `package.json`
- `docs/fitness/**`
- `docs/issues/ai-failures/**`
- `scripts/**`
- `tools/fitness/**`
## 风险
- 调整忽略策略可能改变当前 `pnpm lint` 的覆盖范围。
- budget / hotspot guard 接入后,后续对历史大文件的修改会被更严格地限制。
- 如果阈值设置不合理,可能导致正常改动被误拦截。
## 验证策略
- 运行 `pnpm lint`,确认 `codeql.yml` 不再报 YAML 语法错误。
- 运行 `pnpm run check:file-budget`,确认 budget guard 能返回稳定结果。
- 运行 `pnpm run check:fitness -- --tier fast`,确认新维度已进入治理链路。
## 回滚策略
- 如果忽略策略或 budget 阈值引入误报,优先回退对应配置文件,而不是回退整套治理骨架。
- 如果 CI 因新增 guard 阻塞,可先临时下调阈值或缩小热点清单,再逐步收紧。
# 文档去重与信息架构收敛计划
## 目标
- 消除 `docs/guide/introduction.md` 与 `docs/guide/monorepo.md` 的内容重复。
- 补齐 `docs/guide/structure.md`,把目录结构职责从介绍页中拆出。
- 修正错误链接 `/guide/directory-structure`。
- 清理历史副本型文档 `README copy.md`,避免双入口。
## 范围
- `docs/guide/introduction.md`
- `docs/guide/monorepo.md`
- `docs/guide/structure.md`
- `docs/guide/quick-start.md`
- `packages/cli/templates/vue/README copy.md`
- `apps/web/venus-agentic/venus-agentic-assisant/README copy.md`
## 风险
- 文档链接调整后,如果站点侧边栏或历史引用仍指向旧路径,可能出现跳转失效。
- 删除历史副本后,若有外部引用未更新,可能影响少量旧链接。
- 涉及 `packages/cli/templates/**` 路径,需要确保只清理文档副本,不改变模板行为。
## 验证策略
- 检查 `/guide/structure` 链接引用已替代旧的 `/guide/directory-structure`。
- 确认 `introduction`、`structure`、`monorepo` 的职责边界清晰,不再相互覆盖。
- 检查被删除的 `README copy.md` 没有被仓库内其他文档或脚本引用。
## 回滚策略
- 如果目录结构页或链接调整导致导航不稳定,可单独回退对应 Markdown 文件。
- 如果外部仍依赖历史副本文档,可恢复副本并改为占位跳转说明,而不是恢复旧正文。
# 2026-05-27 AI 设计稿到代码第一阶段执行计划
## 目标
为 `venus` 建立第一阶段 AI 基础设施,让后续“根据 Figma 设计稿生成新项目、老项目需求代码和 UI”的能力有明确落点,而不是停留在 prompt 层面。
本阶段不直接实现完整生成器,而是先补三块基础能力:
- 组件机器描述层
- 项目上下文模型
- AI 设计稿到代码的架构边界
## 范围
本阶段包含:
- 新增 `AI 设计稿到代码` 架构文档
- 新增第一阶段执行计划
- 新增 `contracts/ai/` 下的最小组件 manifest schema
- 为当前 `@venus/common-ui-vue` 补一份最小组件 manifest
本阶段不包含:
- Figma API 接入
- 页面 schema 生成器
- 代码生成器和 patcher 实现
- 自动校验脚本与 CI 接入
- 现有组件库大规模重构
## 背景判断
当前 `venus` 已有:
- 治理骨架:`AGENTS.md`、`contracts/`、`review-trigger`、`fitness`
- 模板交付链:`packages/cli/templates/react`、`packages/cli/templates/vue`
- 少量组件基础:`packages/common-ui/vue-ui`
当前 `venus` 仍缺:
- 统一 design tokens
- 统一组件 manifest
- 面向 AI 的项目上下文模型
- Figma 节点到 `venus` 组件的映射层
因此第一阶段应优先建设“AI 可消费的上下文”,而不是先做端到端生成。
## 风险
- 如果 schema 设计得过重,会拖慢后续试点。
- 如果 schema 设计得过轻,后续无法支撑 Figma 映射和项目增量 patch。
- 当前组件库基础较薄,第一版 manifest 只能覆盖少量现有组件,不能假装已经具备完整 UI 语义层。
- 若没有明确边界,后续容易把“AI 规划”误做成“CLI 功能堆叠”。
## 执行步骤
1. 形成 `docs/architecture/ai-design-to-code.md`
- 说明目标、能力分层、总体架构、仓库落点和阶段路线。
2. 新增 `contracts/ai/component-manifest.schema.json`
- 定义 AI 后续读取组件语义所需的最小字段。
3. 新增 `contracts/ai/common-ui-vue.manifest.json`
- 使用当前 `@venus/common-ui-vue` 组件做首份样例清单。
4. 记录后续第二阶段入口
- design tokens
- project context schema
- figma ingest
- page schema
## 验证策略
- 文档文件通过基本诊断检查
- JSON schema 与 manifest 保持字段一致、可读、可扩展
- `pnpm lint` 不被本次新增文件破坏
## 回滚策略
- 如果 schema 结构明显不合理,可先回滚 `contracts/ai/` 新增文件,不影响现有 CLI 与模板链路
- 如果文档结论需要调整,可单独回滚架构文档和执行计划,不影响仓库已有治理主线
## 下一阶段出口
当本阶段完成后,下一阶段优先事项应为:
1. 建立 `project-context.schema.json`
2. 为 `common-ui-vue` 补更完整的组件属性、插槽、事件和适用场景
3. 设计 `page-schema.schema.json`
4. 评估 `packages/ai/project-intelligence/` 与 `packages/ai/design-mapper/` 的最小包结构
# 2026-05-27 ESLint 历史基线收口计划
## 背景
在完成 `packages/cli/src` 的历史 ESLint 收口后,重新执行全量 `pnpm lint`,发现失败主因已经不在 CLI,而集中在 `apps/uniappX/**`。
本次统计结果显示:
- 全仓 ESLint:`25543` errors,`2841` warnings
- 其中主噪音源几乎全部来自 `apps/uniappX/uniapp-x-tape/**` 与相关 `uvue` / `uts` / `devTools` 历史文件
- 排除 `apps/uniappX/**` 后,剩余为 `0` errors、`75` warnings
这说明当前阻塞主治理链的并不是全仓普遍失控,而是单一历史域把全量 lint 基线淹没了。
## 目标
- 让仓库主治理链上的 `pnpm lint` 恢复可用。
- 保留对普通 TypeScript / Vue / CLI / 文档工具链路径的 ESLint 约束。
- 把 `apps/uniappX/**` 明确标记为“待专项治理”的历史域,而不是继续隐式拖垮全仓基线。
## 决策
本次先在根 `eslint.config.mjs` 中新增:
- `ignores: ["apps/uniappX/**"]`
理由:
1. `uniappX` 路径是高密度历史存量区,单文件错误量可达数百到上千。
2. 这类问题以 `uvue` / `uts` / 历史脚本风格不一致为主,不适合在当前治理主线中逐文件收口。
3. 如果不先隔离该区域,`pnpm lint` 无法作为全仓治理门禁继续使用。
## 非目标
- 本次不尝试一次性修复 `apps/uniappX/**` 的全部 ESLint 问题。
- 本次不改变 `uniappX` 的业务行为和运行时逻辑。
- 本次不把 `warnings` 全部清零,先以恢复全量 lint 可通过为主。
## 后续专项
- 为 `apps/uniappX/**` 单独建立 ESLint 治理计划。
- 区分 `uvue`、`uts`、`devTools`、第三方脚本等子域,逐步建立专用规则或局部 ignore。
- 当 `uniappX` 子域具备可控基线后,再从根 ignore 中逐步收回。
# 执行计划
执行计划用于在高风险或跨边界改动扩散到整个仓库之前,先记录这次改动为什么存在、风险在哪里、如何验证。
## 什么时候需要补计划
- 修改 `packages/cli/**` 或 `packages/cli/templates/**`
- 修改根级工作区配置文件
- 修改治理脚本、contract、hook 或 workflow
- 一次改动跨越多个应用或共享包
## 最小模板
- 目标
- 范围
- 风险
- 验证策略
- 回滚策略
## 命名方式
每个计划文件使用 `YYYY-MM-DD-short-title.md` 命名。
# Fitness 系统
Venus 的 fitness 检查会把仓库策略显式化为可执行的质量维度。
## 分层
- `fast`:本地与 pre-push 的快速反馈
- `normal`:针对共享改动的更完整校验
- `deep`:CI 或定时任务中的深度验证
## 第一版维度
- `CodeQuality`:lint 和类型信号
- `TemplateContract`:模板声明与能力完整性
- `ReviewTriggers`:高风险边界与证据校验
- `Evolvability`:文件预算与历史热点冻结
## 执行方式
- 运行 `pnpm run check:fitness -- --tier fast`
- 引擎会读取 `docs/fitness/*.md` 中的 Markdown frontmatter
- 每个维度都会声明自己的 metric 和执行命令
## 下一步
- 增加 blast-radius 相关指标
- 增加共享包和 API 的 contract 检查
---
{
"dimension": "CodeQuality",
"weight": 0.35,
"tier": "fast",
"threshold": 1,
"metrics":
[
{ "id": "changed-files-lint", "tier": "fast", "command": "pnpm run lint:changed" },
{ "id": "workspace-typecheck", "tier": "fast", "command": "pnpm run check:type" },
],
}
---
# Code Quality
这个维度用于在更高成本的验证开始前,先拦住风格和类型层面的退化。
---
{
"dimension": "Evolvability",
"weight": 0.2,
"tier": "fast",
"threshold": 1,
"metrics": [{ "id": "file-budget-guard", "tier": "fast", "command": "pnpm run check:file-budget" }],
}
---
# Evolvability
这个维度用于限制单文件持续膨胀,并冻结已经超标的历史热点文件。
---
{
"dimension": "ReviewTriggers",
"weight": 0.25,
"tier": "fast",
"threshold": 1,
"metrics": [{ "id": "review-trigger-check", "tier": "fast", "command": "pnpm run review:trigger" }],
}
---
# Review Triggers
这个维度用于防止高风险边界改动在缺少支撑证据的情况下直接通过。
---
{
"dimension": "TemplateContract",
"weight": 0.4,
"tier": "fast",
"threshold": 1,
"metrics": [{ "id": "template-contract-check", "tier": "fast", "command": "pnpm run check:template-contract" }],
}
---
# Template Contract
这个维度用于确保模板的可选能力始终与其声明行为保持一致。
...@@ -58,9 +58,11 @@ venus create <name> [options] ...@@ -58,9 +58,11 @@ venus create <name> [options]
``` ```
**参数说明:** **参数说明:**
- `name` - 项目名称(必需) - `name` - 项目名称(必需)
**选项:** **选项:**
- `--template <name>` - 选择模板 (react|vue),默认 react - `--template <name>` - 选择模板 (react|vue),默认 react
- `--dir <path>` - 自定义生成目录前缀 - `--dir <path>` - 自定义生成目录前缀
- `--root <path>` - 指定生成根目录,默认当前工作目录 - `--root <path>` - 指定生成根目录,默认当前工作目录
...@@ -75,6 +77,7 @@ venus create <name> [options] ...@@ -75,6 +77,7 @@ venus create <name> [options]
- `--version, -v` - 显示版本 - `--version, -v` - 显示版本
**示例:** **示例:**
```bash ```bash
# 创建 Vue 项目 # 创建 Vue 项目
venus create my-vue-app --template vue venus create my-vue-app --template vue
...@@ -93,6 +96,7 @@ venus diagnose [project-path] ...@@ -93,6 +96,7 @@ venus diagnose [project-path]
``` ```
**功能:** **功能:**
- 检测项目是否在 monorepo workspace 中 - 检测项目是否在 monorepo workspace 中
- 分析项目依赖类型(catalog: vs 常规版本) - 分析项目依赖类型(catalog: vs 常规版本)
- 检测依赖冲突 - 检测依赖冲突
...@@ -100,6 +104,7 @@ venus diagnose [project-path] ...@@ -100,6 +104,7 @@ venus diagnose [project-path]
- 提供修复建议 - 提供修复建议
**示例:** **示例:**
```bash ```bash
# 诊断当前目录 # 诊断当前目录
venus diagnose venus diagnose
...@@ -109,6 +114,7 @@ venus diagnose apps/frontend/vue/my-app ...@@ -109,6 +114,7 @@ venus diagnose apps/frontend/vue/my-app
``` ```
**输出示例:** **输出示例:**
``` ```
开始诊断项目... 开始诊断项目...
...@@ -137,11 +143,13 @@ venus fix [project-path] [options] ...@@ -137,11 +143,13 @@ venus fix [project-path] [options]
``` ```
**选项:** **选项:**
- `--dependencies` - 修复依赖问题 - `--dependencies` - 修复依赖问题
- `--config` - 修复配置问题 - `--config` - 修复配置问题
- `--all` - 修复所有问题 - `--all` - 修复所有问题
**示例:** **示例:**
```bash ```bash
# 修复依赖问题 # 修复依赖问题
venus fix apps/frontend/vue/my-app --dependencies venus fix apps/frontend/vue/my-app --dependencies
...@@ -151,6 +159,7 @@ venus fix apps/frontend/vue/my-app --all ...@@ -151,6 +159,7 @@ venus fix apps/frontend/vue/my-app --all
``` ```
**修复内容:** **修复内容:**
- 删除子项目中的重复 node_modules - 删除子项目中的重复 node_modules
- 在 workspace 根目录重新安装依赖 - 在 workspace 根目录重新安装依赖
- 修复配置文件问题 - 修复配置文件问题
...@@ -163,6 +172,7 @@ venus doctor ...@@ -163,6 +172,7 @@ venus doctor
``` ```
**功能:** **功能:**
- 检查 Node.js 版本 - 检查 Node.js 版本
- 检查 pnpm 版本 - 检查 pnpm 版本
- 检查 workspace 配置 - 检查 workspace 配置
...@@ -170,11 +180,13 @@ venus doctor ...@@ -170,11 +180,13 @@ venus doctor
- 检查依赖安装状态 - 检查依赖安装状态
**示例:** **示例:**
```bash ```bash
venus doctor venus doctor
``` ```
**输出示例:** **输出示例:**
``` ```
Venus 环境健康检查 Venus 环境健康检查
...@@ -194,17 +206,20 @@ venus info [project-path] ...@@ -194,17 +206,20 @@ venus info [project-path]
``` ```
**功能:** **功能:**
- 显示项目基本信息 - 显示项目基本信息
- 统计依赖信息 - 统计依赖信息
- 显示配置信息 - 显示配置信息
- 显示构建信息 - 显示构建信息
**示例:** **示例:**
```bash ```bash
venus info apps/frontend/vue/my-app venus info apps/frontend/vue/my-app
``` ```
**输出示例:** **输出示例:**
``` ```
项目信息 项目信息
...@@ -234,15 +249,18 @@ venus ls-templates ...@@ -234,15 +249,18 @@ venus ls-templates
``` ```
**功能:** **功能:**
- 列出所有可用的项目模板 - 列出所有可用的项目模板
- 显示模板的详细信息 - 显示模板的详细信息
**示例:** **示例:**
```bash ```bash
venus ls-templates venus ls-templates
``` ```
**输出示例:** **输出示例:**
``` ```
可用模板: 可用模板:
...@@ -338,7 +356,7 @@ jobs: ...@@ -338,7 +356,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 20.10.0 node-version: 20.10.0
cache: 'pnpm' cache: "pnpm"
- run: pnpm install - run: pnpm install
- run: pnpm venus:build - run: pnpm venus:build
- run: venus doctor - run: venus doctor
......
...@@ -30,6 +30,7 @@ Venus 项目提供了一套完整的配置系统,支持灵活的定制和最 ...@@ -30,6 +30,7 @@ Venus 项目提供了一套完整的配置系统,支持灵活的定制和最
``` ```
**重要配置:** **重要配置:**
- `engines`:定义项目所需的 Node.js 和 pnpm 版本 - `engines`:定义项目所需的 Node.js 和 pnpm 版本
- `scripts`:全局可用的脚本命令 - `scripts`:全局可用的脚本命令
- `devDependencies`:开发工具和配置包 - `devDependencies`:开发工具和配置包
...@@ -52,6 +53,7 @@ catalog: # 依赖版本管理 ...@@ -52,6 +53,7 @@ catalog: # 依赖版本管理
``` ```
**catalog 作用:** **catalog 作用:**
- 统一管理依赖版本 - 统一管理依赖版本
- 确保子项目依赖一致性 - 确保子项目依赖一致性
- 简化依赖更新流程 - 简化依赖更新流程
...@@ -62,11 +64,7 @@ Turbo 构建配置: ...@@ -62,11 +64,7 @@ Turbo 构建配置:
```json ```json
{ {
"globalDependencies": [ "globalDependencies": ["pnpm-lock.yaml", "**/.env.*local", "**/tsconfig*.json"],
"pnpm-lock.yaml",
"**/.env.*local",
"**/tsconfig*.json"
],
"tasks": { "tasks": {
"build": { "build": {
"dependsOn": ["^build"], "dependsOn": ["^build"],
...@@ -81,6 +79,7 @@ Turbo 构建配置: ...@@ -81,6 +79,7 @@ Turbo 构建配置:
``` ```
**重要配置:** **重要配置:**
- `globalDependencies`:全局依赖项,变化时重新构建 - `globalDependencies`:全局依赖项,变化时重新构建
- `tasks`:任务配置和依赖关系 - `tasks`:任务配置和依赖关系
...@@ -110,6 +109,7 @@ Turbo 构建配置: ...@@ -110,6 +109,7 @@ Turbo 构建配置:
``` ```
**catalog 依赖:** **catalog 依赖:**
- `catalog:`:使用 workspace catalog 中定义的版本 - `catalog:`:使用 workspace catalog 中定义的版本
- 自动同步版本更新 - 自动同步版本更新
- 避免版本冲突 - 避免版本冲突
...@@ -135,6 +135,7 @@ TypeScript 配置继承基础配置: ...@@ -135,6 +135,7 @@ TypeScript 配置继承基础配置:
``` ```
**配置说明:** **配置说明:**
- `extends`:继承基础配置 - `extends`:继承基础配置
- `paths`:路径别名配置 - `paths`:路径别名配置
- `types`:额外类型定义 - `types`:额外类型定义
...@@ -144,43 +145,44 @@ TypeScript 配置继承基础配置: ...@@ -144,43 +145,44 @@ TypeScript 配置继承基础配置:
Vite 构建配置: Vite 构建配置:
```typescript ```typescript
import { defineConfig } from 'vite' import { defineConfig } from "vite";
import vue from '@vitejs/plugin-vue' import vue from "@vitejs/plugin-vue";
import { resolve } from 'path' import { resolve } from "path";
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [vue()],
resolve: { resolve: {
alias: { alias: {
'@': resolve(__dirname, 'src'), "@": resolve(__dirname, "src"),
'@venus': resolve(__dirname, '../../packages') "@venus": resolve(__dirname, "../../packages"),
} },
}, },
server: { server: {
port: 3000, port: 3000,
host: true, host: true,
proxy: { proxy: {
'/api': { "/api": {
target: 'http://localhost:8080', target: "http://localhost:8080",
changeOrigin: true changeOrigin: true,
} },
} },
}, },
build: { build: {
outDir: 'dist', outDir: "dist",
sourcemap: true, sourcemap: true,
rollupOptions: { rollupOptions: {
output: { output: {
manualChunks: { manualChunks: {
'vendor': ['vue', 'vue-router', 'pinia'] vendor: ["vue", "vue-router", "pinia"],
} },
} },
} },
} },
}) });
``` ```
**配置要点:** **配置要点:**
- `plugins`:插件配置 - `plugins`:插件配置
- `resolve.alias`:路径别名 - `resolve.alias`:路径别名
- `server`:开发服务器配置 - `server`:开发服务器配置
...@@ -219,9 +221,9 @@ VITE_MOCK_ENABLED=false ...@@ -219,9 +221,9 @@ VITE_MOCK_ENABLED=false
```typescript ```typescript
// 在代码中使用环境变量 // 在代码中使用环境变量
const apiUrl = import.meta.env.VITE_API_BASE_URL const apiUrl = import.meta.env.VITE_API_BASE_URL;
const isDevelopment = import.meta.env.DEV const isDevelopment = import.meta.env.DEV;
const isProduction = import.meta.env.PROD const isProduction = import.meta.env.PROD;
``` ```
## 代码规范配置 ## 代码规范配置
...@@ -253,11 +255,11 @@ export default defineConfig([ ...@@ -253,11 +255,11 @@ export default defineConfig([
export default defineConfig([ export default defineConfig([
{ {
rules: { rules: {
'no-console': 'warn', "no-console": "warn",
'no-debugger': 'error', "no-debugger": "error",
'@typescript-eslint/no-explicit-any': 'warn' "@typescript-eslint/no-explicit-any": "warn",
} },
} },
]); ]);
``` ```
...@@ -271,8 +273,8 @@ export default { ...@@ -271,8 +273,8 @@ export default {
...config, ...config,
semi: true, semi: true,
singleQuote: true, singleQuote: true,
trailingComma: 'es5', trailingComma: "es5",
printWidth: 100 printWidth: 100,
}; };
``` ```
...@@ -285,9 +287,9 @@ import config from "@venus/stylelint-config"; ...@@ -285,9 +287,9 @@ import config from "@venus/stylelint-config";
export default { export default {
...config, ...config,
rules: { rules: {
'selector-class-pattern': '^[a-z][a-z0-9-]*$', "selector-class-pattern": "^[a-z][a-z0-9-]*$",
'property-no-vendor-prefix': true "property-no-vendor-prefix": true,
} },
}; };
``` ```
...@@ -297,28 +299,28 @@ export default { ...@@ -297,28 +299,28 @@ export default {
```typescript ```typescript
// src/router/index.ts // src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from 'vue-router' import type { RouteRecordRaw } from "vue-router";
const routes: RouteRecordRaw[] = [ const routes: RouteRecordRaw[] = [
{ {
path: '/', path: "/",
name: 'Home', name: "Home",
component: () => import('@/views/Home.vue') component: () => import("@/views/Home.vue"),
}, },
{ {
path: '/about', path: "/about",
name: 'About', name: "About",
component: () => import('@/views/About.vue') component: () => import("@/views/About.vue"),
} },
] ];
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
routes routes,
}) });
export default router export default router;
``` ```
### 动态路由 ### 动态路由
...@@ -326,11 +328,11 @@ export default router ...@@ -326,11 +328,11 @@ export default router
```typescript ```typescript
// 根据权限动态添加路由 // 根据权限动态添加路由
const addDynamicRoutes = (permissions: string[]) => { const addDynamicRoutes = (permissions: string[]) => {
const dynamicRoutes = generateRoutesFromPermissions(permissions) const dynamicRoutes = generateRoutesFromPermissions(permissions);
dynamicRoutes.forEach(route => { dynamicRoutes.forEach((route) => {
router.addRoute(route) router.addRoute(route);
}) });
} };
``` ```
## 状态管理配置 ## 状态管理配置
...@@ -339,29 +341,29 @@ const addDynamicRoutes = (permissions: string[]) => { ...@@ -339,29 +341,29 @@ const addDynamicRoutes = (permissions: string[]) => {
```typescript ```typescript
// src/stores/user.ts // src/stores/user.ts
import { defineStore } from 'pinia' import { defineStore } from "pinia";
import { ref, computed } from 'vue' import { ref, computed } from "vue";
export const useUserStore = defineStore('user', () => { export const useUserStore = defineStore("user", () => {
const user = ref<User | null>(null) const user = ref<User | null>(null);
const isLoggedIn = computed(() => !!user.value) const isLoggedIn = computed(() => !!user.value);
const login = async (credentials: LoginCredentials) => { const login = async (credentials: LoginCredentials) => {
const response = await api.login(credentials) const response = await api.login(credentials);
user.value = response.data user.value = response.data;
} };
const logout = () => { const logout = () => {
user.value = null user.value = null;
} };
return { return {
user, user,
isLoggedIn, isLoggedIn,
login, login,
logout logout,
} };
}) });
``` ```
## 国际化配置 ## 国际化配置
...@@ -370,18 +372,18 @@ export const useUserStore = defineStore('user', () => { ...@@ -370,18 +372,18 @@ export const useUserStore = defineStore('user', () => {
```typescript ```typescript
// src/i18n/index.ts // src/i18n/index.ts
import { createI18n } from 'vue-i18n' import { createI18n } from "vue-i18n";
import zh from './locales/zh.json' import zh from "./locales/zh.json";
import en from './locales/en.json' import en from "./locales/en.json";
const i18n = createI18n({ const i18n = createI18n({
legacy: false, legacy: false,
locale: 'zh', locale: "zh",
fallbackLocale: 'en', fallbackLocale: "en",
messages: { zh, en } messages: { zh, en },
}) });
export default i18n export default i18n;
``` ```
## 构建配置 ## 构建配置
...@@ -392,23 +394,23 @@ export default i18n ...@@ -392,23 +394,23 @@ export default i18n
// vite.config.ts // vite.config.ts
export default defineConfig({ export default defineConfig({
build: { build: {
minify: 'terser', minify: "terser",
terserOptions: { terserOptions: {
compress: { compress: {
drop_console: true, drop_console: true,
drop_debugger: true drop_debugger: true,
} },
}, },
rollupOptions: { rollupOptions: {
output: { output: {
chunkFileNames: 'assets/js/[name]-[hash].js', chunkFileNames: "assets/js/[name]-[hash].js",
entryFileNames: 'assets/js/[name]-[hash].js', entryFileNames: "assets/js/[name]-[hash].js",
assetFileNames: 'assets/[ext]/[name]-[hash].[ext]' assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
}
}, },
chunkSizeWarningLimit: 1000 },
} chunkSizeWarningLimit: 1000,
}) },
});
``` ```
## 开发工具配置 ## 开发工具配置
...@@ -422,11 +424,7 @@ export default defineConfig({ ...@@ -422,11 +424,7 @@ export default defineConfig({
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.fixAll.eslint": true "source.fixAll.eslint": true
}, },
"eslint.validate": [ "eslint.validate": ["javascript", "typescript", "vue"],
"javascript",
"typescript",
"vue"
],
"typescript.tsdk": "node_modules/typescript/lib", "typescript.tsdk": "node_modules/typescript/lib",
"vite.devServer.port": 3000 "vite.devServer.port": 3000
} }
......
...@@ -26,11 +26,11 @@ Venus 项目 ...@@ -26,11 +26,11 @@ Venus 项目
```yaml ```yaml
# pnpm-workspace.yaml # pnpm-workspace.yaml
packages: packages:
- 'apps/*' # 应用项目 - "apps/*" # 应用项目
- 'packages/*' # 共享包 - "packages/*" # 共享包
- 'internal/*' # 内部配置 - "internal/*" # 内部配置
- 'scripts/*' # 构建脚本 - "scripts/*" # 构建脚本
- 'docs' # 文档 - "docs" # 文档
catalog: catalog:
# 生产依赖 # 生产依赖
...@@ -66,6 +66,7 @@ catalog: ...@@ -66,6 +66,7 @@ catalog:
Catalog 依赖是 pnpm 的一种机制,允许在 workspace 根目录集中定义依赖版本。 Catalog 依赖是 pnpm 的一种机制,允许在 workspace 根目录集中定义依赖版本。
**优势:** **优势:**
- 📦 **统一版本**:所有项目使用相同版本的依赖 - 📦 **统一版本**:所有项目使用相同版本的依赖
- 🔄 **简化更新**:只需在一处更新版本 - 🔄 **简化更新**:只需在一处更新版本
- 🎯 **避免冲突**:防止版本冲突问题 - 🎯 **避免冲突**:防止版本冲突问题
...@@ -94,8 +95,8 @@ Catalog 依赖是 pnpm 的一种机制,允许在 workspace 根目录集中定 ...@@ -94,8 +95,8 @@ Catalog 依赖是 pnpm 的一种机制,允许在 workspace 根目录集中定
```typescript ```typescript
// 可以正常使用,版本由 catalog 决定 // 可以正常使用,版本由 catalog 决定
import { createApp } from 'vue' import { createApp } from "vue";
import type { Config } from 'vite' import type { Config } from "vite";
``` ```
### 版本管理 ### 版本管理
...@@ -128,6 +129,7 @@ pnpm install ...@@ -128,6 +129,7 @@ pnpm install
Workspace 依赖是指 monorepo 内部的包引用。 Workspace 依赖是指 monorepo 内部的包引用。
**优势:** **优势:**
- 🔗 **实时更新**:修改内部包,立即在项目中生效 - 🔗 **实时更新**:修改内部包,立即在项目中生效
- 🚀 **开发效率**:无需发布即可测试更改 - 🚀 **开发效率**:无需发布即可测试更改
- 🎯 **类型安全**:完整的 TypeScript 类型推导 - 🎯 **类型安全**:完整的 TypeScript 类型推导
...@@ -358,11 +360,13 @@ pnpm update package-name ...@@ -358,11 +360,13 @@ pnpm update package-name
**症状:** 子项目 node_modules 包含完整依赖而非软链接 **症状:** 子项目 node_modules 包含完整依赖而非软链接
**诊断:** **诊断:**
```bash ```bash
venus diagnose venus diagnose
``` ```
**解决:** **解决:**
```bash ```bash
# 删除子项目 node_modules # 删除子项目 node_modules
rm -rf apps/frontend/vue/my-app/node_modules rm -rf apps/frontend/vue/my-app/node_modules
...@@ -379,6 +383,7 @@ venus fix apps/frontend/vue/my-app --dependencies ...@@ -379,6 +383,7 @@ venus fix apps/frontend/vue/my-app --dependencies
**症状:** 不同项目要求不同版本的依赖 **症状:** 不同项目要求不同版本的依赖
**解决:** **解决:**
```json ```json
// 使用 pnpm overrides // 使用 pnpm overrides
{ {
...@@ -395,6 +400,7 @@ venus fix apps/frontend/vue/my-app --dependencies ...@@ -395,6 +400,7 @@ venus fix apps/frontend/vue/my-app --dependencies
**症状:** 引用内部包时类型推导不正确 **症状:** 引用内部包时类型推导不正确
**解决:** **解决:**
```json ```json
// 确保内部包导出类型 // 确保内部包导出类型
// packages/my-utils/package.json // packages/my-utils/package.json
...@@ -417,6 +423,7 @@ venus fix apps/frontend/vue/my-app --dependencies ...@@ -417,6 +423,7 @@ venus fix apps/frontend/vue/my-app --dependencies
**症状:** 依赖安装或解析时间过长 **症状:** 依赖安装或解析时间过长
**解决:** **解决:**
```bash ```bash
# 使用 pnpm 离线缓存 # 使用 pnpm 离线缓存
pnpm config set store-dir ~/.pnpm-store pnpm config set store-dir ~/.pnpm-store
......
# 简介 # 简介
&emsp;&emsp;Venus 是一个基于 Vue 3、TypeScript、Vite 构建的monorepo策略项目仓库管理框架。它采用最新的前端技术栈及依赖工具,为中大型企业提供了多项目统一管理,依赖工具统一维护等解决方案。 Venus 是一个面向中大型前端工程的 monorepo 管理仓库,围绕 `pnpm workspace + Turbo + 共享配置包 + CLI 模板` 建立统一的项目生成、依赖治理和工具链治理能力。
### Monorepo 策略的优势 它的目标不是只提供一个后台模板,而是把“多应用、多模板、多共享包”的协作成本收敛到同一个工作区中,让团队可以在统一约束下持续扩展项目。
采用 Monorepo 策略带来以下核心优势: ## Venus 解决什么问题
- **代码共享与复用** - 多应用共享公共代码、组件和工具,避免重复开发 - 多应用项目的依赖版本不一致
- **统一依赖管理** - 通过 pnpm workspace 集中管理,确保版本一致性 - 各项目 ESLint、TypeScript、构建配置分散维护
- **原子性提交** - 跨包修改一次提交完成,保证变更一致性 - 新项目初始化依赖手工复制模板,质量不稳定
- **跨包重构** - 重构时同步更新所有依赖,IDE 完整支持类型检查 - 跨应用复用组件、工具、配置时缺少统一出口
- **统一工具链** - 共享 ESLint、Prettier、TypeScript 配置,规范一致 - 仓库规模扩大后,变更难以被统一验证和治理
- **高效构建** - 利用 Turbo 实现增量构建和智能缓存,提升构建速度
## 主要技术栈 ## 核心能力
| 技术栈 | 版本 | 作用 | - **统一项目生成**:通过 `venus cli` 生成 React、Vue 等项目模板
| ---------------- | --------- | ------------------------------------------------------------------------- | - **统一依赖管理**:通过 `pnpm workspace` 与 `catalog:` 集中管理版本
| **Vue** | ^3.5.17 | 渐进式 JavaScript 框架,采用 Composition API 提供更好的逻辑复用和代码组织 | - **统一工具链**:共享 ESLint、Prettier、TypeScript、Vite 等配置
| **TypeScript** | ^5.8.3 | 类型系统,提供完整的类型支持,提升开发效率和代码质量 | - **统一构建调度**:通过 Turbo 做增量构建和缓存
| **Vite** | ^7.1.2 | 极速的开发服务器和构建工具,提供快速的 HMR 和优化的生产构建 | - **统一治理入口**:通过 contract、fitness、hook 和文档体系约束高风险改动
| **Pinia** | ^3.0.3 | 新一代状态管理库,更轻量更简洁,替代 Vuex |
| **Vue Router** | ^4.5.1 | 官方路由管理器,支持动态路由和嵌套路由 |
| **Element Plus** | ^2.11.9 | 基于 Vue 3 的企业级 UI 组件库 |
| **Tailwind CSS** | ^3.4.17 | 实用优先的 CSS 框架,快速构建现代化界面 |
| **pnpm** | >=9.12.0 | 快速、节省磁盘空间的包管理器,支持 workspace 管理 |
| **Turbo** | ^2.5.4 | 高性能构建系统,实现增量构建和智能缓存 |
| **qiankun** | ^2.10.16 | 微前端框架,支持多应用统一管理和独立部署 |
| **Node.js** | >=20.10.0 | JavaScript 运行环境,推荐使用 24.12.0 |
## 项目结构 ## 适用场景
``` - 一个仓库内需要维护多个前端应用
venus/ - 需要同时维护模板、共享包和业务项目
├── apps/ # 应用目录 - 希望新项目创建过程标准化、可复制、可验证
│ ├── web/ # Web 应用 - 希望随着仓库扩展,仍能保持一致的工程规范
│ │ ├── venus-agentic/ # 智能体应用
│ │ ├── venus-base/ # 基础应用模板
│ │ └── vue2/ # Vue 2 版本应用
│ ├── miniprogram/ # 小程序应用
│ └── uniapp/ # UniApp 应用
├── packages/ # 公共包
│ ├── charts/ # 图表组件库
│ ├── cli/ # CLI 工具(项目脚手架)
│ ├── common-ui/ # 通用 UI 组件库
│ ├── components/ # 公共组件
│ ├── composables/ # Vue Composables(组合式函数提供可复用的响应式逻辑)
│ ├── constants/ # 常量定义(多应用共享)
│ ├── stores/ # 状态管理(Pinia stores)
│ ├── types/ # 类型定义
│ ├── tools/ # 工具函数(自动路由生成等构建工具和 Vite 插件包)
│ └── utils/ # 通用工具函数包(业务上通用的工具函数)
├── internal/ # 内部工具包
│ ├── lint-configs/ # 代码规范配置
│ │ ├── commitlint-config/ # Commit 规范配置
│ │ ├── eslint-config/ # ESLint 配置
│ │ ├── prettier-config/ # Prettier 配置
│ │ └── stylelint-config/ # Stylelint 配置
│ ├── node-utils/ # Node.js 工具库(文件操作、Git、日期、哈希等)
│ ├── tailwind-config/ # Tailwind CSS 配置
│ ├── tsconfig/ # TypeScript 配置预设
│ └── vite-config/ # Vite 构建配置
├── scripts/ # 构建和开发脚本
│ ├── build/ # 构建相关脚本
│ ├── turbo-run/ # Turbo 运行工具
│ └── vsh/ # Venus Shell 工具(依赖检查、代码检查等)
└── docs/ # 文档站点
```
## 下一步 ## 主要技术栈
- [快速开始](/guide/quick-start) - 快速上手 Venus Admin | 技术栈 | 作用 |
- [项目配置](/guide/configuration) - 了解项目配置 | ----------------------------- | ------------------------- |
- [目录结构](/guide/directory-structure) - 了解项目目录结构 | Vue 3 / React | 应用开发框架 |
| TypeScript | 类型系统与工程约束 |
| Vite | 本地开发与生产构建 |
| pnpm | 依赖安装与 workspace 管理 |
| Turbo | 增量任务编排与缓存 |
| ESLint / Prettier / Stylelint | 代码规范与格式治理 |
## 推荐阅读顺序
1. [快速开始](/guide/quick-start) - 先把项目跑起来
2. [项目结构](/guide/structure) - 了解仓库目录职责
3. [Monorepo 架构](./monorepo.md) - 理解工作区机制与依赖策略
4. [配置指南](/guide/configuration) - 了解共享配置和项目配置
5. [CLI 使用指南](/guide/cli-usage) - 掌握脚手架与诊断工具
...@@ -135,5 +135,5 @@ pnpm install ...@@ -135,5 +135,5 @@ pnpm install
## 下一步 ## 下一步
- [项目配置](/guide/configuration) - 了解如何配置项目 - [项目配置](/guide/configuration) - 了解如何配置项目
- [目录结构](/guide/directory-structure) - 深入了解项目结构 - [目录结构](/guide/structure) - 深入了解项目结构
- [路由和菜单](/guide/router-menu) - 学习路由和菜单配置 - [路由和菜单](/guide/router-menu) - 学习路由和菜单配置
# 项目结构
本页只回答一件事:`venus` 这个仓库里每一层目录分别负责什么。
如果你想了解依赖安装、`catalog:`、`workspace:*`、Turbo 任务编排等机制,请阅读 [Monorepo 架构](./monorepo.md)。
## 顶层结构
```text
venus/
├── apps/ # 应用项目与业务代码
├── packages/ # 可复用的共享包
├── internal/ # 工作区内部配置包
├── scripts/ # 仓库级自动化脚本
├── docs/ # 文档站点与治理文档
├── contracts/ # 可被机器校验的契约
├── tools/ # 治理和质量工具
├── package.json # 根脚本与工作区入口
├── pnpm-workspace.yaml # workspace 与 catalog 配置
└── turbo.json # 任务编排配置
```
## 目录职责
### `apps/`
放置可独立运行的应用项目,包括前端应用、Web 应用、小程序、`uniapp`、`uniappX` 等。
典型子目录:
- `apps/frontend/`:React、Vue 等通用前端项目
- `apps/web/`:Web 场景项目
- `apps/miniprogram/`:小程序项目
- `apps/uniapp/`:UniApp 项目
- `apps/uniappX/`:UniApp X 项目
### `packages/`
放置可被多个应用复用的业务包或工具包。
典型子目录:
- `packages/cli/`:Venus CLI,本仓库的模板交付入口
- `packages/components/`:共享组件
- `packages/composables/`:组合式函数
- `packages/constants/`:共享常量
- `packages/stores/`:状态管理相关包
- `packages/tools/`、`packages/utils/`:通用工具函数
- `packages/types/`:公共类型定义
### `internal/`
放置工作区内部统一配置,不直接面向业务功能,而是面向整个仓库的工程标准。
典型子目录:
- `internal/lint-configs/`:ESLint、Prettier、Stylelint、Commitlint 配置
- `internal/tsconfig/`:TypeScript 配置预设
- `internal/vite-config/`:Vite 配置预设
- `internal/node-utils/`:Node 侧工具函数
- `internal/tailwind-config/`:Tailwind 配置
### `scripts/`
放置仓库级脚本入口,负责构建、诊断、校验、治理流程编排。
例如:
- `scripts/build/`:构建相关脚本
- `scripts/vsh/`:Venus Shell 工具
- `scripts/smart-check.mjs`:治理校验入口
### `docs/`
放置文档站点和治理证据,不只是用户指南,也包括架构、执行计划、fitness 与失败记录。
典型子目录:
- `docs/guide/`:用户指南
- `docs/architecture/`:架构说明
- `docs/exec-plans/`:执行计划
- `docs/fitness/`:质量维度说明
- `docs/issues/`:失败记录与问题沉淀
### `contracts/`
放置仓库中的单一事实源定义,尤其适用于模板能力、共享行为和未来的 API 契约。
当前重点:
- `contracts/templates/`:模板 contract
### `tools/`
放置治理型工具实现,例如 quality engine、review trigger 相关能力。
当前重点:
- `tools/fitness/`:fitness engine 和预算配置
- `tools/review-trigger/`:高风险路径配置
## 如何理解这套结构
- `apps/` 解决“业务和应用放哪里”
- `packages/` 解决“共享代码放哪里”
- `internal/` 解决“统一标准放哪里”
- `scripts/` 和 `tools/` 解决“自动化和治理怎么执行”
- `docs/` 和 `contracts/` 解决“规则、边界和证据放哪里”
## 推荐阅读
- [简介](./introduction.md)
- [Monorepo 架构](./monorepo.md)
- [配置指南](./configuration.md)
- [依赖管理](./dependency.md)
...@@ -32,11 +32,13 @@ pnpm dev --filter=@venus/my-app ...@@ -32,11 +32,13 @@ pnpm dev --filter=@venus/my-app
### 问题 1:依赖重复下载 ### 问题 1:依赖重复下载
**症状:** **症状:**
- 子项目 node_modules 包含完整依赖而非软链接 - 子项目 node_modules 包含完整依赖而非软链接
- 磁盘空间占用过大 - 磁盘空间占用过大
- 安装时间过长 - 安装时间过长
**诊断:** **诊断:**
```bash ```bash
venus diagnose venus diagnose
``` ```
...@@ -44,11 +46,13 @@ venus diagnose ...@@ -44,11 +46,13 @@ venus diagnose
**解决方案:** **解决方案:**
**方法 1:使用 CLI 修复** **方法 1:使用 CLI 修复**
```bash ```bash
venus fix apps/frontend/vue/my-app --dependencies venus fix apps/frontend/vue/my-app --dependencies
``` ```
**方法 2:手动修复** **方法 2:手动修复**
```bash ```bash
# 删除子项目 node_modules # 删除子项目 node_modules
rm -rf apps/frontend/vue/my-app/node_modules rm -rf apps/frontend/vue/my-app/node_modules
...@@ -62,6 +66,7 @@ pnpm install ...@@ -62,6 +66,7 @@ pnpm install
``` ```
**验证:** **验证:**
```bash ```bash
# 检查是否为软链接 # 检查是否为软链接
ls -la apps/frontend/vue/my-app/node_modules/react ls -la apps/frontend/vue/my-app/node_modules/react
...@@ -73,11 +78,13 @@ ls -la apps/frontend/vue/my-app/node_modules/react ...@@ -73,11 +78,13 @@ ls -la apps/frontend/vue/my-app/node_modules/react
### 问题 2:依赖版本冲突 ### 问题 2:依赖版本冲突
**症状:** **症状:**
- 错误信息:`Cannot resolve dependency` - 错误信息:`Cannot resolve dependency`
- 不同项目要求不同版本的依赖 - 不同项目要求不同版本的依赖
- 运行时错误:`TypeError: xxx is not a function` - 运行时错误:`TypeError: xxx is not a function`
**诊断:** **诊断:**
```bash ```bash
# 查看依赖冲突 # 查看依赖冲突
pnpm list --depth=Infinity pnpm list --depth=Infinity
...@@ -89,6 +96,7 @@ pnpm why vue ...@@ -89,6 +96,7 @@ pnpm why vue
**解决方案:** **解决方案:**
**使用 pnpm overrides** **使用 pnpm overrides**
```json ```json
// 在根 package.json 中添加 // 在根 package.json 中添加
{ {
...@@ -103,6 +111,7 @@ pnpm why vue ...@@ -103,6 +111,7 @@ pnpm why vue
``` ```
**然后重新安装:** **然后重新安装:**
```bash ```bash
pnpm install pnpm install
``` ```
...@@ -110,6 +119,7 @@ pnpm install ...@@ -110,6 +119,7 @@ pnpm install
### 问题 3:依赖安装失败 ### 问题 3:依赖安装失败
**症状:** **症状:**
- `pnpm install` 失败 - `pnpm install` 失败
- 网络错误或超时 - 网络错误或超时
- 依赖解析错误 - 依赖解析错误
...@@ -117,6 +127,7 @@ pnpm install ...@@ -117,6 +127,7 @@ pnpm install
**解决方案:** **解决方案:**
**检查网络:** **检查网络:**
```bash ```bash
# 测试 npm 源 # 测试 npm 源
ping registry.npmjs.org ping registry.npmjs.org
...@@ -126,6 +137,7 @@ pnpm config set registry https://registry.npmmirror.com/ ...@@ -126,6 +137,7 @@ pnpm config set registry https://registry.npmmirror.com/
``` ```
**清除缓存:** **清除缓存:**
```bash ```bash
# 清除 pnpm 缓存 # 清除 pnpm 缓存
pnpm store prune pnpm store prune
...@@ -136,6 +148,7 @@ pnpm install ...@@ -136,6 +148,7 @@ pnpm install
``` ```
**使用严格模式:** **使用严格模式:**
```bash ```bash
# 跳过对等依赖检查 # 跳过对等依赖检查
pnpm install --strict-peer-dependencies=false pnpm install --strict-peer-dependencies=false
...@@ -149,12 +162,14 @@ pnpm install --frozen-lockfile ...@@ -149,12 +162,14 @@ pnpm install --frozen-lockfile
### 问题 4:构建内存溢出 ### 问题 4:构建内存溢出
**症状:** **症状:**
- 构建时出现 `JavaScript heap out of memory` - 构建时出现 `JavaScript heap out of memory`
- 构建进程异常终止 - 构建进程异常终止
**解决方案:** **解决方案:**
**增加内存限制:** **增加内存限制:**
```bash ```bash
# 使用 Node 选项 # 使用 Node 选项
export NODE_OPTIONS=--max-old-space-size=8192 export NODE_OPTIONS=--max-old-space-size=8192
...@@ -169,6 +184,7 @@ pnpm build ...@@ -169,6 +184,7 @@ pnpm build
``` ```
**优化构建配置:** **优化构建配置:**
```typescript ```typescript
// vite.config.ts // vite.config.ts
export default defineConfig({ export default defineConfig({
...@@ -177,24 +193,26 @@ export default defineConfig({ ...@@ -177,24 +193,26 @@ export default defineConfig({
rollupOptions: { rollupOptions: {
output: { output: {
manualChunks: { manualChunks: {
'vendor': ['vue', 'vue-router', 'pinia'], vendor: ["vue", "vue-router", "pinia"],
'utils': ['lodash-es'] utils: ["lodash-es"],
} },
} },
} },
} },
}) });
``` ```
### 问题 5:构建速度慢 ### 问题 5:构建速度慢
**症状:** **症状:**
- 构建时间过长 - 构建时间过长
- 每次都重新构建所有内容 - 每次都重新构建所有内容
**解决方案:** **解决方案:**
**使用 Turbo 缓存:** **使用 Turbo 缓存:**
```bash ```bash
# 确保 turbo.json 配置正确 # 确保 turbo.json 配置正确
{ {
...@@ -214,6 +232,7 @@ pnpm build --force ...@@ -214,6 +232,7 @@ pnpm build --force
``` ```
**优化依赖:** **优化依赖:**
```bash ```bash
# 移除未使用的依赖 # 移除未使用的依赖
npx depcheck npx depcheck
...@@ -227,6 +246,7 @@ pnpm remove <unused-package> ...@@ -227,6 +246,7 @@ pnpm remove <unused-package>
### 问题 6:TypeScript 类型错误 ### 问题 6:TypeScript 类型错误
**症状:** **症状:**
- 类型检查失败 - 类型检查失败
- `Cannot find module` - `Cannot find module`
- 类型推导不正确 - 类型推导不正确
...@@ -234,6 +254,7 @@ pnpm remove <unused-package> ...@@ -234,6 +254,7 @@ pnpm remove <unused-package>
**解决方案:** **解决方案:**
**检查 TypeScript 配置:** **检查 TypeScript 配置:**
```json ```json
// tsconfig.json // tsconfig.json
{ {
...@@ -250,6 +271,7 @@ pnpm remove <unused-package> ...@@ -250,6 +271,7 @@ pnpm remove <unused-package>
``` ```
**更新类型定义:** **更新类型定义:**
```bash ```bash
# 安装缺失的类型 # 安装缺失的类型
pnpm add -D @types/node @types/lodash-es pnpm add -D @types/node @types/lodash-es
...@@ -259,6 +281,7 @@ pnpm run typecheck ...@@ -259,6 +281,7 @@ pnpm run typecheck
``` ```
**清理缓存:** **清理缓存:**
```bash ```bash
# 删除 TypeScript 缓存 # 删除 TypeScript 缓存
rm -rf node_modules/.cache rm -rf node_modules/.cache
...@@ -273,12 +296,14 @@ pnpm run typecheck ...@@ -273,12 +296,14 @@ pnpm run typecheck
### 问题 7:端口被占用 ### 问题 7:端口被占用
**症状:** **症状:**
- `Error: listen EADDRINUSE: address already in use :::3000` - `Error: listen EADDRINUSE: address already in use :::3000`
- 开发服务器启动失败 - 开发服务器启动失败
**解决方案:** **解决方案:**
**查找占用端口的进程:** **查找占用端口的进程:**
```bash ```bash
# Windows # Windows
netstat -ano | findstr :3000 netstat -ano | findstr :3000
...@@ -288,6 +313,7 @@ lsof -i :3000 ...@@ -288,6 +313,7 @@ lsof -i :3000
``` ```
**终止进程:** **终止进程:**
```bash ```bash
# Windows # Windows
taskkill /PID <进程ID> /F taskkill /PID <进程ID> /F
...@@ -297,40 +323,44 @@ kill -9 <进程ID> ...@@ -297,40 +323,44 @@ kill -9 <进程ID>
``` ```
**修改端口:** **修改端口:**
```typescript ```typescript
// vite.config.ts // vite.config.ts
export default defineConfig({ export default defineConfig({
server: { server: {
port: 3001, // 修改为其他端口 port: 3001, // 修改为其他端口
host: true host: true,
} },
}) });
``` ```
### 问题 8:热更新不工作 ### 问题 8:热更新不工作
**症状:** **症状:**
- 修改代码后页面不更新 - 修改代码后页面不更新
- 需要手动刷新浏览器 - 需要手动刷新浏览器
**解决方案:** **解决方案:**
**检查 Vite 配置:** **检查 Vite 配置:**
```typescript ```typescript
// vite.config.ts // vite.config.ts
export default defineConfig({ export default defineConfig({
server: { server: {
hmr: { hmr: {
overlay: true // 显示错误覆盖层 overlay: true, // 显示错误覆盖层
}, },
watch: { watch: {
usePolling: true // 在某些文件系统上需要轮询 usePolling: true, // 在某些文件系统上需要轮询
} },
} },
}) });
``` ```
**检查文件监听限制:** **检查文件监听限制:**
```bash ```bash
# Linux/Mac 增加文件监听限制 # Linux/Mac 增加文件监听限制
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
...@@ -338,6 +368,7 @@ sudo sysctl -p ...@@ -338,6 +368,7 @@ sudo sysctl -p
``` ```
**清除缓存:** **清除缓存:**
```bash ```bash
# 删除 Vite 缓存 # 删除 Vite 缓存
rm -rf node_modules/.vite rm -rf node_modules/.vite
...@@ -351,12 +382,14 @@ pnpm dev ...@@ -351,12 +382,14 @@ pnpm dev
### 问题 9:CLI 命令未找到 ### 问题 9:CLI 命令未找到
**症状:** **症状:**
- `venus: command not found` - `venus: command not found`
- `venus is not recognized` - `venus is not recognized`
**解决方案:** **解决方案:**
**检查安装:** **检查安装:**
```bash ```bash
# 检查是否安装 # 检查是否安装
which venus which venus
...@@ -366,6 +399,7 @@ pnpm list -g @venus/cli ...@@ -366,6 +399,7 @@ pnpm list -g @venus/cli
``` ```
**重新安装:** **重新安装:**
```bash ```bash
# 全局安装 # 全局安装
pnpm add -g @venus/cli pnpm add -g @venus/cli
...@@ -375,6 +409,7 @@ pnpm venus <command> ...@@ -375,6 +409,7 @@ pnpm venus <command>
``` ```
**设置 PATH:** **设置 PATH:**
```bash ```bash
# 添加到 PATH # 添加到 PATH
export PATH="$PATH:$(pnpm store path)" export PATH="$PATH:$(pnpm store path)"
...@@ -387,12 +422,14 @@ source ~/.bashrc ...@@ -387,12 +422,14 @@ source ~/.bashrc
### 问题 10:CLI 诊断失败 ### 问题 10:CLI 诊断失败
**症状:** **症状:**
- `venus diagnose` 报错 - `venus diagnose` 报错
- 无法识别项目类型 - 无法识别项目类型
**解决方案:** **解决方案:**
**检查项目结构:** **检查项目结构:**
```bash ```bash
# 确保在正确的目录中 # 确保在正确的目录中
ls package.json ls package.json
...@@ -402,6 +439,7 @@ ls pnpm-workspace.yaml ...@@ -402,6 +439,7 @@ ls pnpm-workspace.yaml
``` ```
**使用详细模式:** **使用详细模式:**
```bash ```bash
# 查看详细错误信息 # 查看详细错误信息
venus diagnose --verbose venus diagnose --verbose
...@@ -411,6 +449,7 @@ venus doctor ...@@ -411,6 +449,7 @@ venus doctor
``` ```
**手动诊断:** **手动诊断:**
```bash ```bash
# 检查 package.json # 检查 package.json
cat package.json | jq '.dependencies, .devDependencies' cat package.json | jq '.dependencies, .devDependencies'
...@@ -424,17 +463,20 @@ cat pnpm-workspace.yaml ...@@ -424,17 +463,20 @@ cat pnpm-workspace.yaml
### 问题 11:Pre-commit 钩子失败 ### 问题 11:Pre-commit 钩子失败
**症状:** **症状:**
- Git commit 失败 - Git commit 失败
- `husky - pre-commit hook exited with code` - `husky - pre-commit hook exited with code`
**解决方案:** **解决方案:**
**跳过钩子(仅测试用):** **跳过钩子(仅测试用):**
```bash ```bash
git commit --no-verify -m "message" git commit --no-verify -m "message"
``` ```
**修复代码问题:** **修复代码问题:**
```bash ```bash
# 运行检查 # 运行检查
pnpm lint pnpm lint
...@@ -446,6 +488,7 @@ git commit -m "message" ...@@ -446,6 +488,7 @@ git commit -m "message"
``` ```
**重新安装钩子:** **重新安装钩子:**
```bash ```bash
# 重新安装 husky/lefthook # 重新安装 husky/lefthook
pnpm install pnpm install
...@@ -457,12 +500,14 @@ npx husky install ...@@ -457,12 +500,14 @@ npx husky install
### 问题 12:Commitlint 错误 ### 问题 12:Commitlint 错误
**症状:** **症状:**
- `Subject may not be empty` - `Subject may not be empty`
- `type must be one of [feat, fix, docs...]` - `type must be one of [feat, fix, docs...]`
**解决方案:** **解决方案:**
**使用正确的提交格式:** **使用正确的提交格式:**
```bash ```bash
# 正确格式 # 正确格式
git commit -m "feat: 添加新功能" git commit -m "feat: 添加新功能"
...@@ -474,12 +519,14 @@ git commit -m "添加新功能" # 缺少类型 ...@@ -474,12 +519,14 @@ git commit -m "添加新功能" # 缺少类型
``` ```
**使用交互式提交:** **使用交互式提交:**
```bash ```bash
# 使用 czg 创建规范的 commit # 使用 czg 创建规范的 commit
pnpm commit pnpm commit
``` ```
**查看提交规范:** **查看提交规范:**
```bash ```bash
# 查看帮助 # 查看帮助
npx commitlint --help npx commitlint --help
...@@ -493,25 +540,28 @@ echo "feat: new feature" | npx commitlint ...@@ -493,25 +540,28 @@ echo "feat: new feature" | npx commitlint
### 问题 13:测试运行失败 ### 问题 13:测试运行失败
**症状:** **症状:**
- 测试用例不执行 - 测试用例不执行
- 测试结果不正确 - 测试结果不正确
**解决方案:** **解决方案:**
**检查测试配置:** **检查测试配置:**
```javascript ```javascript
// vitest.config.ts // vitest.config.ts
export default defineConfig({ export default defineConfig({
test: { test: {
globals: true, globals: true,
environment: 'jsdom', environment: "jsdom",
include: ['**/*.test.ts', '**/*.spec.ts'], include: ["**/*.test.ts", "**/*.spec.ts"],
exclude: ['node_modules', 'dist'] exclude: ["node_modules", "dist"],
} },
}) });
``` ```
**运行测试:** **运行测试:**
```bash ```bash
# 运行所有测试 # 运行所有测试
pnpm test pnpm test
...@@ -531,12 +581,14 @@ pnpm test --ui ...@@ -531,12 +581,14 @@ pnpm test --ui
### 问题 14:首次启动慢 ### 问题 14:首次启动慢
**症状:** **症状:**
- 项目首次启动时间长 - 项目首次启动时间长
- 冷启动速度慢 - 冷启动速度慢
**解决方案:** **解决方案:**
**优化依赖:** **优化依赖:**
```bash ```bash
# 移除不必要的依赖 # 移除不必要的依赖
npx depcheck npx depcheck
...@@ -547,21 +599,23 @@ pnpm remove <unused-package> ...@@ -547,21 +599,23 @@ pnpm remove <unused-package>
``` ```
**优化 Vite 配置:** **优化 Vite 配置:**
```typescript ```typescript
// vite.config.ts // vite.config.ts
export default defineConfig({ export default defineConfig({
optimizeDeps: { optimizeDeps: {
include: ['vue', 'vue-router', 'pinia'] include: ["vue", "vue-router", "pinia"],
}, },
build: { build: {
commonjsOptions: { commonjsOptions: {
transformMixedEsModules: true transformMixedEsModules: true,
} },
} },
}) });
``` ```
**使用 Turbo 缓存:** **使用 Turbo 缓存:**
```bash ```bash
# Turbo 会缓存构建结果 # Turbo 会缓存构建结果
# 后续启动会更快 # 后续启动会更快
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!