Commit 058d6dae by liimin

chore(deps): 更新项目版本并移除前端依赖

- 将项目版本从 0.0.1 更新到 0.1.0
- 移除 antd、react-router-dom 和 zustand 依赖
- 清理 pnpm-lock.yaml 中的相关包引用
- 重命名应用目录从 venus-my-app 到 test-workspace-deps
- 删除多个 UI 组件相关的依赖包
1 parent 15c97535
# Venus 项目文档系统完善和 CLI 工具增强任务计划
## 第一阶段:文档系统完善
- [x] Task 1: 完善主 README.md 文档
- [x] Task 2: 创建核心文档文件
- [x] Task 3: 优化现有文档内容
- [x] Task 4: 更新版本和变更信息
- [x] Task 5: 创建诊断工具功能
- [x] Task 6: 创建项目诊断命令
- [x] Task 7: 创建项目修复命令
- [x] Task 8: 创建健康检查命令
- [x] Task 9: 创建项目信息命令
- [x] Task 10: 增强 CLI 主入口
- 4.1: 更新根目录 package.json 中的版本号
- 4.2: 更新 docs/changelog.md 中的变更记录
- 4.3: 同步所有相关文件中的版本信息
- 4.4: 添加新功能的变更说明
## 第二阶段:CLI 工具增强
- [x] Task 5: 创建诊断工具功能
- 5.1: 创建诊断工具文件 (packages/cli/src/utils/diagnostics.ts)
- 5.2: 实现项目依赖分析功能
- 5.3: 实现配置文件检查功能
- 5.4: 实现依赖冲突检测功能
- 5.5: 添加诊断报告生成功能
- [x] Task 6: 创建项目诊断命令
- 6.1: 创建诊断命令文件 (packages/cli/src/commands/diagnose.ts)
- 6.2: 实现诊断主逻辑和流程控制
- 6.3: 添加命令行参数解析
- 6.4: 实现友好的诊断输出格式
- 6.5: 添加错误处理和用户提示
- [x] Task 7: 创建项目修复命令
- 7.1: 创建修复命令文件 (packages/cli/src/commands/fix.ts)
- 7.2: 实现依赖问题自动修复逻辑
- 7.3: 实现配置问题自动修复逻辑
- 7.4: 添加修复进度提示
- 7.5: 实现修复结果验证功能
- [x] Task 8: 创建健康检查命令
- 8.1: 创建健康检查命令文件 (packages/cli/src/commands/doctor.ts)
- 8.2: 实现环境检查功能 (Node.js, pnpm, Git)
- 8.3: 实现配置验证功能
- 8.4: 实现依赖安装状态检查
- 8.5: 添加检查结果的友好展示
- [x] Task 9: 创建项目信息命令
- 9.1: 创建项目信息命令文件 (packages/cli/src/commands/info.ts)
- 9.2: 实现项目基本信息展示
- 9.3: 实现依赖信息统计
- 9.4: 实现项目配置信息展示
- 9.5: 添加信息格式化输出
- [x] Task 10: 增强 CLI 主入口
- 10.1: 在主入口中注册新命令
- 10.2: 更新帮助信息和使用说明
- 10.3: 添加命令别名和快捷方式
- 10.4: 优化错误提示和用户体验
- 10.5: 添加版本信息和更新提示
## 第三阶段:集成测试和优化
- [x] Task 11: 测试文档系统
- [x] Task 12: 测试 CLI 工具功能
- [x] Task 13: 性能和用户体验优化
- [x] Task 14: 文档最终完善
- [x] Task 15: 版本发布准备
- [x] Task 16: 质量保证
- 16.1: 执行完整的代码检查
- 16.2: 运行所有测试用例
- 16.3: 验证文档完整性
- 16.4: 检查版本一致性
- 16.5: 确认发布就绪状态
...@@ -24,21 +24,59 @@ pnpm preview ...@@ -24,21 +24,59 @@ pnpm preview
``` ```
docs/ docs/
├── .vitepress/ # VitePress 配置 ├── guide/ # 用户指南
│ └── config.ts # 配置文件 │ ├── quick-start.md # 快速开始
├── components/ # 组件文档 │ ├── introduction.md # 项目介绍
│ ├── overview.md # 组件总览 │ ├── structure.md # 项目结构
│ ├── form.md # 表单组件 │ ├── router-menu.md # 路由菜单
│ └── ... │ ├── permission.md # 权限管理
├── api/ # API 参考 │ ├── cli-usage.md # CLI 使用指南 ⭐ 新增
│ ├── core.md # 核心 API │ ├── configuration.md # 配置指南 ⭐ 新增
│ ├── utils.md # 工具函数 │ ├── monorepo.md # Monorepo 架构 ⭐ 新增
│ └── ... │ ├── dependency.md # 依赖管理 ⭐ 新增
│ └── troubleshooting.md # 故障排查 ⭐ 新增
├── micro/ # 微前端文档
│ ├── intruduction.md
│ └── docs/
├── index.md # 首页 ├── index.md # 首页
├── changelog.md # 更新日志 ├── changelog.md # 更新日志
└── README.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。 如果你发现文档有任何问题或想要改进文档,欢迎提交 Pull Request。
......
# 更新日志 # 更新日志
## v1.0.0 (2025-12-10) ## v0.1.0 (2026-05-26)
### ✨ 新增功能
- **CLI 工具增强**:
- 新增项目诊断命令 (`venus diagnose`)
- 新增项目修复命令 (`venus fix`)
- 新增健康检查命令 (`venus doctor`)
- 新增项目信息查看命令 (`venus info`)
- **依赖管理优化**:
- 修复了 monorepo 环境中依赖重复下载问题
- 实现了智能依赖安装策略
- 添加了依赖冲突检测功能
- 完善了 catalog: 依赖处理逻辑
### 📝 文档完善
- **主 README 文档**:
- 填充了项目简介和核心价值
- 添加了升级提示和版本升级指南
- 完善了预览章节和文档链接
- **新增核心文档**:
- CLI 使用指南 (`docs/guide/cli-usage.md`)
- 配置指南 (`docs/guide/configuration.md`)
- Monorepo 架构说明 (`docs/guide/monorepo.md`)
- 依赖管理指南 (`docs/guide/dependency.md`)
- 故障排查指南 (`docs/guide/troubleshooting.md`)
### 🐛 问题修复
- 修复了 CLI 在子项目中执行 `pnpm install` 导致依赖重复下载的问题
- 修复了 catalog: 依赖软链接建立失败的问题
- 修复了文档链接无效的问题
- 修复了版本号不一致的问题
### 🔧 工具链优化
- 优化了 pnpm workspace 配置
- 改进了 Turbo 构建配置
- 完善了 ESLint 和 Prettier 配置
- 添加了依赖分析工具
### 📚 文档优化
- 统一了文档格式和风格
- 添加了详细的代码示例
- 补充了最佳实践指南
- 完善了故障排查文档
---
## v0.0.1 (2025-12-10)
- 基本框架划分/基础设施搭建/完成基础库初版 - 基本框架划分/基础设施搭建/完成基础库初版
- 第三方依赖及本地依赖管理配置 - 第三方依赖及本地依赖管理配置
......
# CLI 使用指南
Venus CLI 是一个强大的命令行工具,用于快速创建、诊断和修复 Venus 项目。
## 安装
### 全局安装
```bash
# 使用 pnpm
pnpm add -g @venus/cli
# 使用 npm
npm install -g @venus/cli
# 使用 yarn
yarn global add @venus/cli
```
### 本地使用
如果您已经在 Venus monorepo 项目中,可以直接使用:
```bash
pnpm venus <command>
```
## 命令列表
### 项目创建
#### 交互式创建(推荐)
```bash
venus create
```
进入交互式模式,CLI 会引导您完成项目配置:
```bash
? 请输入项目名称: my-app
? 请选择模板类型:
○ React
● Vue
? 请输入构建目录前缀: apps/frontend/vue
? 是否立即安装依赖? Yes
? 是否启用 HTTP 请求库? No
? 是否启用路由 (Router)? Yes
? 是否启用状态管理 (Store)? Yes
? 请选择 UI 库 (可选): element-plus
? 是否启用 ESLint? Yes
```
#### 命令行创建
```bash
venus create <name> [options]
```
**参数说明:**
- `name` - 项目名称(必需)
**选项:**
- `--template <name>` - 选择模板 (react|vue),默认 react
- `--dir <path>` - 自定义生成目录前缀
- `--root <path>` - 指定生成根目录,默认当前工作目录
- `--no-install` - 跳过依赖安装
- `--axios` - 注入 HTTP 请求库
- `--router` - 注入路由
- `--store` - 注入状态管理
- `--ui <name>` - 注入 UI 库
- `--eslint` - 注入 ESLint 配置
- `--force` - 目标目录非空时强制写入
- `--help, -h` - 显示帮助
- `--version, -v` - 显示版本
**示例:**
```bash
# 创建 Vue 项目
venus create my-vue-app --template vue
# 创建 React 项目并启用所有功能
venus create my-react-app --template react --axios --router --store --ui antd --eslint
# 跳过依赖安装
venus create my-app --no-install
```
### 项目诊断
```bash
venus diagnose [project-path]
```
**功能:**
- 检测项目是否在 monorepo workspace 中
- 分析项目依赖类型(catalog: vs 常规版本)
- 检测依赖冲突
- 检查配置文件完整性
- 提供修复建议
**示例:**
```bash
# 诊断当前目录
venus diagnose
# 诊断指定项目
venus diagnose apps/frontend/vue/my-app
```
**输出示例:**
```
开始诊断项目...
✓ Workspace 环境: d:\work\venus
✓ pnpm-workspace.yaml: 存在
✓ package.json: 存在且有效
依赖分析:
- Catalog 依赖: 是
- 常规依赖: 否
- 总依赖数: 8
配置文件检查:
✓ tsconfig.json
✓ vite.config.ts
✓ .eslintrc.js
✓ .prettierrc
诊断完成!未发现问题。
```
### 项目修复
```bash
venus fix [project-path] [options]
```
**选项:**
- `--dependencies` - 修复依赖问题
- `--config` - 修复配置问题
- `--all` - 修复所有问题
**示例:**
```bash
# 修复依赖问题
venus fix apps/frontend/vue/my-app --dependencies
# 修复所有问题
venus fix apps/frontend/vue/my-app --all
```
**修复内容:**
- 删除子项目中的重复 node_modules
- 在 workspace 根目录重新安装依赖
- 修复配置文件问题
- 更新过期的配置
### 健康检查
```bash
venus doctor
```
**功能:**
- 检查 Node.js 版本
- 检查 pnpm 版本
- 检查 workspace 配置
- 检查 Git 配置
- 检查依赖安装状态
**示例:**
```bash
venus doctor
```
**输出示例:**
```
Venus 环境健康检查
Node.js: v24.12.0 ✓ (需要 >=20.10.0)
pnpm: 10.14.0 ✓ (需要 >=9.12.0)
Workspace 配置: ✓
Git 配置: ✓
依赖安装: ✓
健康检查完成!环境正常。
```
### 项目信息
```bash
venus info [project-path]
```
**功能:**
- 显示项目基本信息
- 统计依赖信息
- 显示配置信息
- 显示构建信息
**示例:**
```bash
venus info apps/frontend/vue/my-app
```
**输出示例:**
```
项目信息
名称: @venus/my-app
版本: 0.0.0
模板: Vue
路径: apps/frontend/vue/my-app
依赖信息:
- 生产依赖: 4
- 开发依赖: 6
- 总计: 10
配置信息:
- TypeScript: ✓
- Vite: ✓
- Router: ✓
- Store: ✓
- UI: element-plus
- ESLint: ✓
```
### 列出模板
```bash
venus ls-templates
```
**功能:**
- 列出所有可用的项目模板
- 显示模板的详细信息
**示例:**
```bash
venus ls-templates
```
**输出示例:**
```
可用模板:
React:
- react: React 18 + TypeScript + Vite
- react-antd: React + Ant Design
- react-tailwind: React + Tailwind CSS
Vue:
- vue: Vue 3 + TypeScript + Vite
- vue-element-plus: Vue + Element Plus
- vue-naive: Vue + Naive UI
```
### 帮助信息
```bash
venus --help
venus <command> --help
```
## 常见使用场景
### 场景 1:创建新的 Vue 项目
```bash
# 交互式创建
venus create
# 按提示选择 Vue 模板,启用需要的功能
# 或使用命令行
venus create my-vue-app --template vue --router --store --ui element-plus
```
### 场景 2:诊断项目问题
```bash
# 检查项目是否有问题
venus diagnose apps/frontend/vue/my-app
# 如果发现问题,运行修复
venus fix apps/frontend/vue/my-app --all
```
### 场景 3:修复依赖重复下载问题
```bash
# 诊断依赖问题
venus diagnose
# 修复依赖问题
venus fix --dependencies
```
### 场景 4:环境检查
```bash
# 检查开发环境是否正常
venus doctor
# 如果发现问题,按照提示修复
```
## 高级用法
### 批量创建项目
```bash
#!/bin/bash
# 批量创建多个项目
projects=("app1" "app2" "app3")
for project in "${projects[@]}"; do
venus create "$project" --template vue --router --store --ui element-plus --eslint
done
```
### 集成到 CI/CD
```yaml
# .github/workflows/check.yml
name: Project Health Check
on: [push, pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 9.12.0
- uses: actions/setup-node@v3
with:
node-version: 20.10.0
cache: 'pnpm'
- run: pnpm install
- run: pnpm venus:build
- run: venus doctor
- run: venus diagnose apps/frontend/vue/my-app
```
## 故障排查
### 问题:命令未找到
```bash
# 检查是否正确安装
which venus
# 如果未找到,重新安装
pnpm add -g @venus/cli
# 或在项目中使用
pnpm venus <command>
```
### 问题:诊断失败
```bash
# 检查项目路径是否正确
ls apps/frontend/vue/my-app
# 检查 package.json 是否存在
cat apps/frontend/vue/my-app/package.json
# 运行详细诊断
venus diagnose --verbose
```
### 问题:修复失败
```bash
# 检查权限
ls -la apps/frontend/vue/my-app
# 手动删除 node_modules 后重试
rm -rf apps/frontend/vue/my-app/node_modules
venus fix apps/frontend/vue/my-app --dependencies
```
## 最佳实践
1. **创建项目前**:运行 `venus doctor` 确保环境正常
2. **项目创建后**:运行 `venus diagnose` 检查项目配置
3. **遇到问题时**:先运行 `venus diagnose` 诊断,再使用 `venus fix` 修复
4. **定期维护**:定期运行 `venus doctor` 确保开发环境健康
5. **团队协作**:在 CI/CD 中集成健康检查,确保代码质量
## 版本信息
```bash
venus --version
# 输出: Venus CLI v0.1.0
```
## 相关文档
- [项目配置](./configuration.md)
- [Monorepo 架构](./monorepo.md)
- [依赖管理](./dependency.md)
- [故障排查](./troubleshooting.md)
\ No newline at end of file \ No newline at end of file
# Venus 项目配置指南
Venus 项目提供了一套完整的配置系统,支持灵活的定制和最佳实践。
## 核心配置文件
### 1. 根目录配置
#### package.json
根目录的 `package.json` 包含了全局脚本和依赖管理配置:
```json
{
"name": "venus",
"version": "0.1.0",
"private": true,
"engines": {
"node": ">=20.10.0",
"pnpm": ">=9.12.0"
},
"scripts": {
"dev": "turbo-run dev",
"build": "cross-env NODE_OPTIONS=--max-old-space-size=8192 turbo-run build",
"check": "pnpm run check:circular && pnpm run check:dep && pnpm run check:type && pnpm check:cspell",
"format": "vsh lint --format",
"lint": "vsh lint"
}
}
```
**重要配置:**
- `engines`:定义项目所需的 Node.js 和 pnpm 版本
- `scripts`:全局可用的脚本命令
- `devDependencies`:开发工具和配置包
#### pnpm-workspace.yaml
定义 Monorepo 的工作空间包:
```yaml
packages:
- internal/* # 内部配置包
- packages/* # 共享包
- apps/* # 应用项目
- scripts/* # 构建脚本
catalog: # 依赖版本管理
"vue": ^3.5.17
"react": ^18.2.0
"typescript": ^5.8.3
```
**catalog 作用:**
- 统一管理依赖版本
- 确保子项目依赖一致性
- 简化依赖更新流程
#### turbo.json
Turbo 构建配置:
```json
{
"globalDependencies": [
"pnpm-lock.yaml",
"**/.env.*local",
"**/tsconfig*.json"
],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}
```
**重要配置:**
- `globalDependencies`:全局依赖项,变化时重新构建
- `tasks`:任务配置和依赖关系
### 2. 项目配置
#### package.json
子项目的 `package.json` 使用 catalog 依赖:
```json
{
"name": "@venus/my-app",
"version": "0.0.1",
"private": true,
"type": "module",
"dependencies": {
"vue": "catalog:",
"vue-router": "catalog:",
"pinia": "catalog:"
},
"devDependencies": {
"typescript": "catalog:",
"vite": "catalog:",
"@types/vue": "catalog:"
}
}
```
**catalog 依赖:**
- `catalog:`:使用 workspace catalog 中定义的版本
- 自动同步版本更新
- 避免版本冲突
#### tsconfig.json
TypeScript 配置继承基础配置:
```json
{
"extends": "@venus/tsconfig/base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@venus/*": ["../../packages/*/src"]
},
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"exclude": ["node_modules", "dist"]
}
```
**配置说明:**
- `extends`:继承基础配置
- `paths`:路径别名配置
- `types`:额外类型定义
#### vite.config.ts
Vite 构建配置:
```typescript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
'@venus': resolve(__dirname, '../../packages')
}
},
server: {
port: 3000,
host: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
},
build: {
outDir: 'dist',
sourcemap: true,
rollupOptions: {
output: {
manualChunks: {
'vendor': ['vue', 'vue-router', 'pinia']
}
}
}
}
})
```
**配置要点:**
- `plugins`:插件配置
- `resolve.alias`:路径别名
- `server`:开发服务器配置
- `build`:构建配置
## 环境变量配置
### .env 文件
项目支持不同环境的配置:
```
.env # 所有环境
.env.local # 本地开发(git 忽略)
.env.development # 开发环境
.env.production # 生产环境
```
**配置示例:**
```bash
# .env
VITE_APP_TITLE=Venus App
VITE_API_BASE_URL=/api
# .env.development
VITE_API_BASE_URL=http://localhost:8080/api
VITE_MOCK_ENABLED=true
# .env.production
VITE_API_BASE_URL=https://api.example.com
VITE_MOCK_ENABLED=false
```
**使用方式:**
```typescript
// 在代码中使用环境变量
const apiUrl = import.meta.env.VITE_API_BASE_URL
const isDevelopment = import.meta.env.DEV
const isProduction = import.meta.env.PROD
```
## 代码规范配置
### ESLint 配置
项目使用扁平化 ESLint 配置:
```javascript
// eslint.config.mjs
import { defineConfig } from "@venus/eslint-config";
export default defineConfig([
{
files: ["src/**/*.ts", "src/**/*.vue"],
languageOptions: {
parserOptions: {
project: ["./tsconfig.json"],
tsconfigRootDir: import.meta.dirname,
},
},
},
]);
```
**自定义规则:**
```javascript
export default defineConfig([
{
rules: {
'no-console': 'warn',
'no-debugger': 'error',
'@typescript-eslint/no-explicit-any': 'warn'
}
}
]);
```
### Prettier 配置
```javascript
// prettier.config.mjs
import config from "@venus/prettier-config";
export default {
...config,
semi: true,
singleQuote: true,
trailingComma: 'es5',
printWidth: 100
};
```
### Stylelint 配置
```javascript
// stylelint.config.mjs
import config from "@venus/stylelint-config";
export default {
...config,
rules: {
'selector-class-pattern': '^[a-z][a-z0-9-]*$',
'property-no-vendor-prefix': true
}
};
```
## 路由配置
### Vue Router
```typescript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
export default router
```
### 动态路由
```typescript
// 根据权限动态添加路由
const addDynamicRoutes = (permissions: string[]) => {
const dynamicRoutes = generateRoutesFromPermissions(permissions)
dynamicRoutes.forEach(route => {
router.addRoute(route)
})
}
```
## 状态管理配置
### Pinia Store
```typescript
// src/stores/user.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useUserStore = defineStore('user', () => {
const user = ref<User | null>(null)
const isLoggedIn = computed(() => !!user.value)
const login = async (credentials: LoginCredentials) => {
const response = await api.login(credentials)
user.value = response.data
}
const logout = () => {
user.value = null
}
return {
user,
isLoggedIn,
login,
logout
}
})
```
## 国际化配置
### vue-i18n
```typescript
// src/i18n/index.ts
import { createI18n } from 'vue-i18n'
import zh from './locales/zh.json'
import en from './locales/en.json'
const i18n = createI18n({
legacy: false,
locale: 'zh',
fallbackLocale: 'en',
messages: { zh, en }
})
export default i18n
```
## 构建配置
### 生产环境优化
```typescript
// vite.config.ts
export default defineConfig({
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
},
rollupOptions: {
output: {
chunkFileNames: 'assets/js/[name]-[hash].js',
entryFileNames: 'assets/js/[name]-[hash].js',
assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
}
},
chunkSizeWarningLimit: 1000
}
})
```
## 开发工具配置
### VS Code 设置
```json
// .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"typescript",
"vue"
],
"typescript.tsdk": "node_modules/typescript/lib",
"vite.devServer.port": 3000
}
```
### 推荐扩展
```json
// .vscode/extensions.json
{
"recommendations": [
"vue.volar",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"stylelint.vscode-stylelint",
"bradlc.vscode-tailwindcss"
]
}
```
## 配置验证
### 检查配置
使用 CLI 工具检查配置:
```bash
# 检查当前项目配置
venus diagnose
# 检查配置文件
venus doctor
```
### 常见配置问题
**问题 1:路径别名不工作**
```typescript
// 确保 tsconfig.json 和 vite.config.ts 中的路径别名一致
// tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
// vite.config.ts
export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, 'src')
}
}
})
```
**问题 2:环境变量未生效**
```bash
# 确保环境变量以 VITE_ 开头(开发环境)
VITE_API_BASE_URL=http://localhost:8080
# 使用时注意
const apiUrl = import.meta.env.VITE_API_BASE_URL // ✓
const apiUrl = process.env.VITE_API_BASE_URL // ✗
```
**问题 3:ESLint 配置不生效**
```javascript
// 确保使用 flat config 格式
// eslint.config.mjs (正确)
import { defineConfig } from "@venus/eslint-config";
export default defineConfig([
// 你的配置
]);
// .eslintrc.js (已废弃,不支持)
module.exports = {
// 配置
};
```
## 最佳实践
1. **使用 catalog 依赖**:在 monorepo 中优先使用 `catalog:` 依赖
2. **继承配置**:继承项目的基础配置,避免重复
3. **环境变量**:区分开发和生产环境
4. **路径别名**:统一使用 `@` 别名
5. **代码规范**:保持团队统一的代码风格
6. **定期检查**:使用 CLI 工具定期检查配置
## 相关文档
- [CLI 使用指南](./cli-usage.md)
- [Monorepo 架构](./monorepo.md)
- [依赖管理](./dependency.md)
- [故障排查](./troubleshooting.md)
\ No newline at end of file \ No newline at end of file
# Venus 依赖管理指南
Venus 采用 pnpm workspace 和 catalog 的依赖管理机制,确保项目间依赖的一致性和效率。
## 依赖管理架构
### 三层依赖结构
```
Venus 项目
├── catalog 依赖 (全局定义)
│ ├── vue: ^3.5.17
│ ├── react: ^18.2.0
│ └── typescript: ^5.8.3
├── workspace 依赖 (内部包)
│ ├── @venus/components: workspace:*
│ ├── @venus/utils: workspace:*
│ └── @venus/cli: workspace:*
└── 项目依赖 (项目特定)
├── axios: ^1.7.9
└── custom-lib: ^1.0.0
```
### pnpm workspace 配置
```yaml
# pnpm-workspace.yaml
packages:
- 'apps/*' # 应用项目
- 'packages/*' # 共享包
- 'internal/*' # 内部配置
- 'scripts/*' # 构建脚本
- 'docs' # 文档
catalog:
# 生产依赖
"vue": ^3.5.17
"react": ^18.2.0
"react-dom": ^18.2.0
"react-router-dom": ^6.27.0
"pinia": ^3.0.3
"zustand": ^4.4.0
"axios": ^1.7.9
# UI 库
"element-plus": ^2.11.9
"ant-design-vue": ^4.2.6
"antd": ^5.19.4
# 开发工具
"typescript": ^5.8.3
"vite": ^7.1.2
"@vitejs/plugin-vue": ^6.0.1
"@vitejs/plugin-react": ^4.2.0
# 代码质量
"eslint": ^9.30.1
"prettier": ^3.6.2
"stylelint": ^16.21.0
```
## Catalog 依赖
### 什么是 Catalog 依赖
Catalog 依赖是 pnpm 的一种机制,允许在 workspace 根目录集中定义依赖版本。
**优势:**
- 📦 **统一版本**:所有项目使用相同版本的依赖
- 🔄 **简化更新**:只需在一处更新版本
- 🎯 **避免冲突**:防止版本冲突问题
- 💾 **节省空间**:硬链接共享依赖
### 使用 Catalog 依赖
**在项目 package.json 中:**
```json
{
"dependencies": {
"vue": "catalog:",
"react-dom": "catalog:",
"pinia": "catalog:"
},
"devDependencies": {
"typescript": "catalog:",
"vite": "catalog:",
"eslint": "catalog:"
}
}
```
**在项目中引用:**
```typescript
// 可以正常使用,版本由 catalog 决定
import { createApp } from 'vue'
import type { Config } from 'vite'
```
### 版本管理
**查看当前 catalog 版本:**
```bash
# 查看所有 catalog 依赖
cat pnpm-workspace.yaml
# 或使用 CLI
venus info
```
**更新 catalog 依赖版本:**
```bash
# 更新单个依赖
# 编辑 pnpm-workspace.yaml,修改版本
"vue": ^3.5.18
# 然后在根目录重新安装
pnpm install
```
## Workspace 依赖
### 什么是 Workspace 依赖
Workspace 依赖是指 monorepo 内部的包引用。
**优势:**
- 🔗 **实时更新**:修改内部包,立即在项目中生效
- 🚀 **开发效率**:无需发布即可测试更改
- 🎯 **类型安全**:完整的 TypeScript 类型推导
### 使用 Workspace 依赖
**在项目 package.json 中:**
```json
{
"dependencies": {
"@venus/components": "workspace:*",
"@venus/utils": "workspace:*"
}
}
```
**协议类型:**
```json
{
"dependencies": {
// 最新版本(推荐)
"@venus/components": "workspace:*",
// 语义化版本
"@venus/components": "workspace:^",
// 兼容版本
"@venus/components": "workspace:~",
// 特定版本
"@venus/components": "workspace:0.1.0"
}
}
```
**开发内部包:**
```bash
# 创建新包
mkdir packages/my-utils
cd packages/my-utils
pnpm init
# 在应用中引用
cd apps/frontend/vue/my-app
pnpm add workspace:@venus/my-utils
# 开发时可以直接看到更改
# 无需重新安装或发布
```
## 常规依赖
### 添加常规依赖
**项目特定依赖:**
```bash
# 在项目目录中执行
cd apps/frontend/vue/my-app
# 添加生产依赖
pnpm add axios lodash-es
# 添加开发依赖
pnpm add -D @types/lodash-es
# 添加确切版本
pnpm add axios@1.7.9
```
**添加到根 catalog:**
```bash
# 1. 在 pnpm-workspace.yaml 中添加
"axios": ^1.7.9
# 2. 在项目中使用 catalog:
# package.json
{
"dependencies": {
"axios": "catalog:"
}
}
# 3. 在根目录安装
cd ../../..
pnpm install
```
### 依赖范围
```json
{
"dependencies": {
// 生产依赖 - 运行时必需
"vue": "catalog:",
"axios": "^1.7.9"
},
"devDependencies": {
// 开发依赖 - 仅开发时需要
"typescript": "catalog:",
"vite": "catalog:",
"@types/node": "catalog:"
},
"peerDependencies": {
// 对等依赖 - 宿主项目必须提供
"vue": "^3.5.0"
},
"optionalDependencies": {
// 可选依赖 - 不强制要求
"fsevents": "*"
}
}
```
## 依赖分析
### 查看依赖关系
```bash
# 查看项目依赖树
pnpm list --depth=0
# 查看详细依赖树
pnpm list
# 查看特定依赖
pnpm list vue
# 查看依赖版本来源
pnpm why vue
```
### 依赖冲突检测
```bash
# 检查依赖冲突
pnpm list --depth=Infinity
# 使用 CLI 诊断
venus diagnose
# 检查依赖安全
pnpm audit
```
## 依赖优化
### 1. 移除未使用的依赖
```bash
# 分析未使用的依赖
npx depcheck
# 移除特定依赖
pnpm remove lodash
# 移除所有未使用的依赖
npx depcheck --fix
```
### 2. 优化依赖大小
```bash
# 查看依赖大小
pnpm list --json | jq '.[] | {name: .name, size: .size}'
# 使用更小的替代品
# 例如:moment.js → date-fns
pnpm remove moment
pnpm add date-fns
```
### 3. 使用 pnpm overrides
```json
{
"pnpm": {
"overrides": {
// 强制使用特定版本
"vue": "catalog:",
"react": "catalog:",
// 修复子依赖问题
"mini-css-extract-plugin": "^2.7.0"
}
}
}
```
## 依赖更新
### 批量更新
```bash
# 查找可更新的依赖
pnpm outdated
# 交互式更新
npx taze major # 主版本更新
npx taze minor # 次版本更新
npx taze patch # 补丁更新
# 自动更新并安装
npx taze -w
```
### 安全更新
```bash
# 检查安全漏洞
pnpm audit
# 自动修复安全漏洞
pnpm audit --fix
# 手动修复
pnpm update package-name
```
## 常见问题解决
### 问题 1:依赖重复下载
**症状:** 子项目 node_modules 包含完整依赖而非软链接
**诊断:**
```bash
venus diagnose
```
**解决:**
```bash
# 删除子项目 node_modules
rm -rf apps/frontend/vue/my-app/node_modules
# 在根目录重新安装
pnpm install
# 或使用 CLI 自动修复
venus fix apps/frontend/vue/my-app --dependencies
```
### 问题 2:版本冲突
**症状:** 不同项目要求不同版本的依赖
**解决:**
```json
// 使用 pnpm overrides
{
"pnpm": {
"overrides": {
"axios": "catalog:"
}
}
}
```
### 问题 3:内部包类型问题
**症状:** 引用内部包时类型推导不正确
**解决:**
```json
// 确保内部包导出类型
// packages/my-utils/package.json
{
"main": "./dist/index.js",
"module": "./dist/index.esm.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
"require": "./dist/index.js"
}
}
}
```
### 问题 4:依赖解析缓慢
**症状:** 依赖安装或解析时间过长
**解决:**
```bash
# 使用 pnpm 离线缓存
pnpm config set store-dir ~/.pnpm-store
# 使用国内镜像
pnpm config set registry https://registry.npmmirror.com/
# 使用严格模式跳过检查
pnpm install --strict-peer-dependencies=false
```
## 最佳实践
### 1. 依赖分类
```json
{
"dependencies": {
// 只放运行时必需的依赖
"vue": "catalog:",
"axios": "^1.7.9"
},
"devDependencies": {
// 开发工具都放在这里
"typescript": "catalog:",
"vite": "catalog:",
"eslint": "catalog:"
}
}
```
### 2. 版本控制
```json
// 使用固定版本号
{
"dependencies": {
// ✓ 好的做法
"axios": "1.7.9",
// ✗ 不好的做法
"axios": "*"
}
}
```
### 3. 定期清理
```bash
# 定期检查未使用的依赖
npx depcheck
# 清理缓存
pnpm store prune
# 删除重复的依赖
pnpm dedupe
```
### 4. 文档化依赖
```json
{
"dependencies": {
"vue": "catalog:" // Vue.js 框架
},
"devDependencies": {
"typescript": "catalog:" // TypeScript 编译器
}
}
```
## 工具命令
### Venus CLI 命令
```bash
# 诊断项目依赖
venus diagnose
# 修复依赖问题
venus fix --dependencies
# 查看项目信息
venus info
# 健康检查
venus doctor
```
### pnpm 命令
```bash
# 安装依赖
pnpm install
# 添加依赖
pnpm add <package>
# 移除依赖
pnpm remove <package>
# 更新依赖
pnpm update <package>
# 检查过时依赖
pnpm outdated
# 查看依赖树
pnpm list
# 审计安全
pnpm audit
```
## 相关文档
- [CLI 使用指南](./cli-usage.md)
- [配置指南](./configuration.md)
- [Monorepo 架构](./monorepo.md)
- [故障排查](./troubleshooting.md)
\ No newline at end of file \ No newline at end of file
# Venus Monorepo 架构说明
Venus 采用 pnpm + Turbo 的 Monorepo 架构,提供高效的多项目管理解决方案。
## 什么是 Monorepo
Monorepo(单一仓库)是一种软件工程策略,将多个项目存储在同一个代码仓库中。
**优势:**
- 📦 **统一依赖管理**:共享依赖,减少重复安装
- 🔧 **统一工具链**:所有项目使用相同的构建、测试、部署工具
- 🔄 **原子化提交**:相关代码变更在同一个 commit 中
- 🧪 **统一代码质量**:强制执行相同的代码规范和质量标准
- 📊 **代码复用**:轻松在项目间共享代码和组件
- 🚀 **高效开发**:依赖关系清晰的增量构建
## Venus 架构概览
```
venus/
├── apps/ # 应用项目
│ ├── frontend/ # 前端项目
│ │ ├── react/ # React 项目
│ │ └── vue/ # Vue 项目
│ ├── miniprogram/ # 原生小程序
│ ├── uniapp/ # UniApp 项目
│ ├── uniappX/ # UniAppX 项目
│ └── web/ # Web 项目
├── packages/ # 共享包
│ ├── cli/ # CLI 工具
│ ├── components/ # 共享组件
│ ├── composables/ # 组合式函数
│ ├── constants/ # 全局常量
│ ├── stores/ # 状态管理
│ ├── tools/ # 工具函数
│ ├── types/ # TypeScript 类型
│ └── utils/ # 实用工具
├── internal/ # 内部配置包
│ ├── lint-configs/ # 代码规范配置
│ ├── node-utils/ # Node 工具
│ ├── tailwind-config/ # Tailwind 配置
│ ├── tsconfig/ # TypeScript 配置
│ └── vite-config/ # Vite 配置
├── scripts/ # 构建脚本
├── docs/ # 文档
├── pnpm-workspace.yaml # 工作空间配置
├── turbo.json # Turbo 配置
├── package.json # 根 package.json
└── tsconfig.json # TypeScript 基础配置
```
## 核心技术栈
### pnpm
pnpm 是快速、节省磁盘空间的包管理器,通过硬链接实现依赖共享。
**特点:**
- 🚀 快速安装:比 npm/yarn 快 2-3 倍
- 💾 节省空间:共享相同的依赖,节省磁盘空间
- 🔒 严格模式:防止访问未声明的依赖
- 📦 Monorepo 原生支持:内置 workspace 功能
**workspace 配置:**
```yaml
# pnpm-workspace.yaml
packages:
- 'apps/*'
- 'packages/*'
- 'internal/*'
- 'scripts/*'
- 'docs'
catalog:
"vue": ^3.5.17
"react": ^18.2.0
"typescript": ^5.8.3
```
**catalog 依赖:**
```json
// 使用 catalog 版本
{
"dependencies": {
"vue": "catalog:", // 使用 catalog 定义的版本
"vue-router": "catalog:"
}
}
// 常规依赖
{
"dependencies": {
"axios": "^1.7.9" // 指定具体版本
}
}
```
### Turbo
Turbo 是一个构建系统,为 JavaScript/TypeScript 代码库提供高性能的构建。
**特点:**
- ⚡ 增量构建:只重新构建改变的包
- 🧠 智能缓存:缓存构建结果,避免重复工作
- 🔗 任务依赖:定义任务之间的依赖关系
- 📊 并行执行:并行执行独立的任务
- 🎯 远程缓存:团队共享构建缓存
**配置示例:**
```json
{
"globalDependencies": [
"pnpm-lock.yaml",
"**/.env.*local",
"**/tsconfig*.json"
],
"globalEnv": ["NODE_ENV"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", "dist.zip"]
},
"dev": {
"cache": false,
"persistent": true
},
"test": {
"dependsOn": ["build"]
}
}
}
```
**依赖关系:**
- `^build`:依赖当前包的所有依赖的 build 任务
- `~build`:依赖当前包的直接依赖的 build 任务
## 工作原理
### 依赖安装流程
```
用户执行 pnpm install
↓
读取 pnpm-workspace.yaml
↓
分析所有 package.json
↓
解析 catalog: 依赖
↓
在 .pnpm/store 中安装依赖
↓
创建硬链接到各项目 node_modules
↓
生成 pnpm-lock.yaml
```
### 构建流程
```
用户执行 pnpm build
↓
Turbo 分析任务依赖图
↓
检查缓存
↓
命中缓存 → 直接返回结果
↓
未命中缓存 → 执行构建任务
↓
保存构建结果到缓存
↓
返回构建结果
```
## 包分类
### 1. 应用包 (apps/)
**职责:** 独立运行的应用程序
**分类:**
- `apps/frontend/react/` - React 前端应用
- `apps/frontend/vue/` - Vue 前端应用
- `apps/miniprogram/` - 微信小程序
- `apps/uniapp/` - UniApp 跨端应用
- `apps/uniappX/` - UniAppX 应用
- `apps/web/` - Web 应用
**特点:**
- 独立的 package.json
- 可以独立运行和部署
- 依赖 packages/ 和 internal/ 中的包
### 2. 共享包 (packages/)
**职责:** 可被多个应用共享的代码和工具
**分类:**
- `packages/cli/` - CLI 工具
- `packages/components/` - 共享 UI 组件
- `packages/composables/` - Vue 组合式函数
- `packages/constants/` - 全局常量
- `packages/stores/` - Pinia 状态管理
- `packages/tools/` - 工具函数
- `packages/types/` - TypeScript 类型定义
- `packages/utils/` - 实用工具
**特点:**
- 被多个应用引用
- 版本统一管理
- 可以独立发布
### 3. 内部配置包 (internal/)
**职责:** 项目配置和工具
**分类:**
- `internal/lint-configs/` - 代码规范配置
- `internal/node-utils/` - Node 工具
- `internal/tailwind-config/` - Tailwind 配置
- `internal/tsconfig/` - TypeScript 配置
- `internal/vite-config/` - Vite 配置
**特点:**
- 内部使用,不对外发布
- 统一的配置标准
- 确保团队一致性
## 依赖管理
### 依赖类型
```json
{
"dependencies": {
// 生产依赖
"vue": "catalog:", // catalog 依赖
"axios": "^1.7.9", // 常规依赖
"lodash-es": "^4.17.21" // 常规依赖
},
"devDependencies": {
// 开发依赖
"typescript": "catalog:", // catalog 依赖
"vite": "catalog:", // catalog 依赖
"@types/node": "catalog:" // catalog 依赖
},
"peerDependencies": {
// 对等依赖
"vue": "^3.5.0"
},
"optionalDependencies": {
// 可选依赖
"fsevents": "*"
}
}
```
### 依赖引用
**在同一 monorepo 中引用:**
```json
{
"dependencies": {
// 引用内部包
"@venus/components": "workspace:*",
"@venus/utils": "workspace:*",
"@venus/cli": "workspace:*"
}
}
```
**发布后引用:**
```json
{
"dependencies": {
// 引用已发布的包
"@venus/components": "^0.1.0"
}
}
```
## 构建系统
### 构建任务
```json
{
"scripts": {
"dev": "turbo-run dev",
"build": "turbo-run build",
"test": "turbo-run test",
"lint": "turbo-run lint",
"format": "turbo-run format"
}
}
```
### 增量构建
Turbo 只重新构建改变的包:
```bash
# 只重新构建改变的包
pnpm build
# 强制重新构建所有包
pnpm build --force
# 清除缓存后构建
pnpm build --filter=@venus/components
```
### 并行构建
Turbo 自动并行执行独立的任务:
```bash
# 并行执行所有 dev 任务
pnpm dev
# 并行执行所有 test 任务
pnpm test
```
## 开发工作流
### 1. 创建新项目
```bash
# 使用 CLI 创建项目
venus create my-app --template vue
# 项目会自动创建在 apps/frontend/vue/my-app
# 依赖会正确使用 catalog: 配置
```
### 2. 添加共享代码
```bash
# 在 packages 中创建新包
mkdir packages/my-utils
# 在 packages/my-utils 中初始化
pnpm init
# 在应用中引用
pnpm add workspace:@venus/my-utils --filter=@venus/my-app
```
### 3. 开发和构建
```bash
# 开发模式
pnpm dev --filter=@venus/my-app
# 构建
pnpm build --filter=@venus/my-app
# 构建所有包
pnpm build
```
### 4. 测试
```bash
# 运行测试
pnpm test --filter=@venus/my-app
# 运行所有测试
pnpm test
```
## 常见问题
### 问题 1:依赖重复下载
**症状:** 子项目 node_modules 包含完整依赖
**原因:** 在子项目中执行 `pnpm install`
**解决:**
```bash
# 删除子项目 node_modules
rm -rf apps/frontend/vue/my-app/node_modules
# 在根目录重新安装
pnpm install
# 或使用 CLI 修复
venus fix apps/frontend/vue/my-app --dependencies
```
### 问题 2:构建缓存问题
**症状:** 代码更改后构建结果不变
**解决:**
```bash
# 清除 Turbo 缓存
pnpm build --force
# 或删除缓存目录
rm -rf .turbo
# 重新构建
pnpm build
```
### 问题 3:依赖冲突
**症状:** 不同项目依赖版本冲突
**解决:**
```json
// 在根 package.json 中使用 overrides
{
"pnpm": {
"overrides": {
"vue": "catalog:",
"react": "catalog:"
}
}
}
```
## 性能优化
### 1. 使用 Turbo 缓存
```json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
}
}
}
```
### 2. 优化依赖安装
```bash
# 只安装必要的依赖
pnpm install --frozen-lockfile
# 使用严格模式
pnpm install --strict-peer-dependencies
```
### 3. 并行执行
```bash
# 并行执行独立的任务
pnpm build --parallel
# 限制并发数
pnpm build --concurrency=4
```
## 最佳实践
1. **使用 catalog 依赖**:确保依赖版本一致
2. **定义任务依赖**:让 Turbo 优化构建顺序
3. **合理使用缓存**:提高构建速度
4. **避免循环依赖**:保持包的清晰结构
5. **定期清理**:清理不需要的包和依赖
6. **统一配置**:使用 internal 配置包
7. **文档完善**:为每个包编写文档
## 相关文档
- [CLI 使用指南](./cli-usage.md)
- [配置指南](./configuration.md)
- [依赖管理](./dependency.md)
- [故障排查](./troubleshooting.md)
\ No newline at end of file \ No newline at end of file
# Venus 故障排查指南
本文档收集了 Venus 项目开发中常见的故障和解决方案。
## 快速诊断
### 第一步:环境检查
```bash
# 运行健康检查
venus doctor
# 检查项目配置
venus diagnose
# 查看项目信息
venus info
```
### 第二步:查看错误日志
```bash
# 查看构建日志
pnpm build --filter=@venus/my-app
# 查看开发服务器日志
pnpm dev --filter=@venus/my-app
```
## 依赖相关故障
### 问题 1:依赖重复下载
**症状:**
- 子项目 node_modules 包含完整依赖而非软链接
- 磁盘空间占用过大
- 安装时间过长
**诊断:**
```bash
venus diagnose
```
**解决方案:**
**方法 1:使用 CLI 修复**
```bash
venus fix apps/frontend/vue/my-app --dependencies
```
**方法 2:手动修复**
```bash
# 删除子项目 node_modules
rm -rf apps/frontend/vue/my-app/node_modules
# 删除子项目 package-lock.json(如果存在)
rm -f apps/frontend/vue/my-app/package-lock.json
# 在根目录重新安装
cd d:/work/venus
pnpm install
```
**验证:**
```bash
# 检查是否为软链接
ls -la apps/frontend/vue/my-app/node_modules/react
# 应该显示类似:
# react -> ../../../.pnpm/react@18.3.1/node_modules/react
```
### 问题 2:依赖版本冲突
**症状:**
- 错误信息:`Cannot resolve dependency`
- 不同项目要求不同版本的依赖
- 运行时错误:`TypeError: xxx is not a function`
**诊断:**
```bash
# 查看依赖冲突
pnpm list --depth=Infinity
# 检查特定依赖
pnpm why vue
```
**解决方案:**
**使用 pnpm overrides**
```json
// 在根 package.json 中添加
{
"pnpm": {
"overrides": {
"vue": "catalog:",
"react": "catalog:",
"axios": "^1.7.9"
}
}
}
```
**然后重新安装:**
```bash
pnpm install
```
### 问题 3:依赖安装失败
**症状:**
- `pnpm install` 失败
- 网络错误或超时
- 依赖解析错误
**解决方案:**
**检查网络:**
```bash
# 测试 npm 源
ping registry.npmjs.org
# 切换到国内镜像
pnpm config set registry https://registry.npmmirror.com/
```
**清除缓存:**
```bash
# 清除 pnpm 缓存
pnpm store prune
# 删除 node_modules 重新安装
rm -rf node_modules apps/*/node_modules packages/*/node_modules
pnpm install
```
**使用严格模式:**
```bash
# 跳过对等依赖检查
pnpm install --strict-peer-dependencies=false
# 使用冻结 lockfile
pnpm install --frozen-lockfile
```
## 构建相关故障
### 问题 4:构建内存溢出
**症状:**
- 构建时出现 `JavaScript heap out of memory`
- 构建进程异常终止
**解决方案:**
**增加内存限制:**
```bash
# 使用 Node 选项
export NODE_OPTIONS=--max-old-space-size=8192
pnpm build
# 或在 package.json 中配置
{
"scripts": {
"build": "cross-env NODE_OPTIONS=--max-old-space-size=8192 turbo-run build"
}
}
```
**优化构建配置:**
```typescript
// vite.config.ts
export default defineConfig({
build: {
chunkSizeWarningLimit: 1000,
rollupOptions: {
output: {
manualChunks: {
'vendor': ['vue', 'vue-router', 'pinia'],
'utils': ['lodash-es']
}
}
}
}
})
```
### 问题 5:构建速度慢
**症状:**
- 构建时间过长
- 每次都重新构建所有内容
**解决方案:**
**使用 Turbo 缓存:**
```bash
# 确保 turbo.json 配置正确
{
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
}
}
}
# 使用增量构建
pnpm build
# 强制重新构建
pnpm build --force
```
**优化依赖:**
```bash
# 移除未使用的依赖
npx depcheck
pnpm remove <unused-package>
# 使用轻量级替代品
# moment.js → date-fns
# lodash → lodash-es
```
### 问题 6:TypeScript 类型错误
**症状:**
- 类型检查失败
- `Cannot find module`
- 类型推导不正确
**解决方案:**
**检查 TypeScript 配置:**
```json
// tsconfig.json
{
"extends": "@venus/tsconfig/base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@venus/*": ["../../packages/*/src"]
},
"types": ["vite/client"]
}
}
```
**更新类型定义:**
```bash
# 安装缺失的类型
pnpm add -D @types/node @types/lodash-es
# 重新生成类型
pnpm run typecheck
```
**清理缓存:**
```bash
# 删除 TypeScript 缓存
rm -rf node_modules/.cache
rm -rf .tsbuildinfo
# 重新检查
pnpm run typecheck
```
## 开发服务器故障
### 问题 7:端口被占用
**症状:**
- `Error: listen EADDRINUSE: address already in use :::3000`
- 开发服务器启动失败
**解决方案:**
**查找占用端口的进程:**
```bash
# Windows
netstat -ano | findstr :3000
# Linux/Mac
lsof -i :3000
```
**终止进程:**
```bash
# Windows
taskkill /PID <进程ID> /F
# Linux/Mac
kill -9 <进程ID>
```
**修改端口:**
```typescript
// vite.config.ts
export default defineConfig({
server: {
port: 3001, // 修改为其他端口
host: true
}
})
```
### 问题 8:热更新不工作
**症状:**
- 修改代码后页面不更新
- 需要手动刷新浏览器
**解决方案:**
**检查 Vite 配置:**
```typescript
// vite.config.ts
export default defineConfig({
server: {
hmr: {
overlay: true // 显示错误覆盖层
},
watch: {
usePolling: true // 在某些文件系统上需要轮询
}
}
})
```
**检查文件监听限制:**
```bash
# Linux/Mac 增加文件监听限制
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
```
**清除缓存:**
```bash
# 删除 Vite 缓存
rm -rf node_modules/.vite
# 重启开发服务器
pnpm dev
```
## CLI 工具故障
### 问题 9:CLI 命令未找到
**症状:**
- `venus: command not found`
- `venus is not recognized`
**解决方案:**
**检查安装:**
```bash
# 检查是否安装
which venus
# 检查全局安装位置
pnpm list -g @venus/cli
```
**重新安装:**
```bash
# 全局安装
pnpm add -g @venus/cli
# 或在项目中使用
pnpm venus <command>
```
**设置 PATH:**
```bash
# 添加到 PATH
export PATH="$PATH:$(pnpm store path)"
# 或在 shell 配置文件中添加
echo 'export PATH="$PATH:$(pnpm store path)"' >> ~/.bashrc
source ~/.bashrc
```
### 问题 10:CLI 诊断失败
**症状:**
- `venus diagnose` 报错
- 无法识别项目类型
**解决方案:**
**检查项目结构:**
```bash
# 确保在正确的目录中
ls package.json
# 确保文件存在
ls pnpm-workspace.yaml
```
**使用详细模式:**
```bash
# 查看详细错误信息
venus diagnose --verbose
# 检查配置
venus doctor
```
**手动诊断:**
```bash
# 检查 package.json
cat package.json | jq '.dependencies, .devDependencies'
# 检查 workspace 配置
cat pnpm-workspace.yaml
```
## Git 相关故障
### 问题 11:Pre-commit 钩子失败
**症状:**
- Git commit 失败
- `husky - pre-commit hook exited with code`
**解决方案:**
**跳过钩子(仅测试用):**
```bash
git commit --no-verify -m "message"
```
**修复代码问题:**
```bash
# 运行检查
pnpm lint
pnpm format
# 修复后提交
git add .
git commit -m "message"
```
**重新安装钩子:**
```bash
# 重新安装 husky/lefthook
pnpm install
# 或手动设置
npx husky install
```
### 问题 12:Commitlint 错误
**症状:**
- `Subject may not be empty`
- `type must be one of [feat, fix, docs...]`
**解决方案:**
**使用正确的提交格式:**
```bash
# 正确格式
git commit -m "feat: 添加新功能"
git commit -m "fix: 修复bug"
git commit -m "docs: 更新文档"
# 错误格式
git commit -m "添加新功能" # 缺少类型
```
**使用交互式提交:**
```bash
# 使用 czg 创建规范的 commit
pnpm commit
```
**查看提交规范:**
```bash
# 查看帮助
npx commitlint --help
# 测试 commit 消息
echo "feat: new feature" | npx commitlint
```
## 测试相关故障
### 问题 13:测试运行失败
**症状:**
- 测试用例不执行
- 测试结果不正确
**解决方案:**
**检查测试配置:**
```javascript
// vitest.config.ts
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
include: ['**/*.test.ts', '**/*.spec.ts'],
exclude: ['node_modules', 'dist']
}
})
```
**运行测试:**
```bash
# 运行所有测试
pnpm test
# 运行特定测试
pnpm test <test-file>
# 监听模式
pnpm test --watch
# UI 模式
pnpm test --ui
```
## 性能相关问题
### 问题 14:首次启动慢
**症状:**
- 项目首次启动时间长
- 冷启动速度慢
**解决方案:**
**优化依赖:**
```bash
# 移除不必要的依赖
npx depcheck
pnpm remove <unused-package>
# 使用更轻量的替代品
# 重的包 → 轻量级的包
```
**优化 Vite 配置:**
```typescript
// vite.config.ts
export default defineConfig({
optimizeDeps: {
include: ['vue', 'vue-router', 'pinia']
},
build: {
commonjsOptions: {
transformMixedEsModules: true
}
}
})
```
**使用 Turbo 缓存:**
```bash
# Turbo 会缓存构建结果
# 后续启动会更快
pnpm dev
```
## 获取帮助
### 使用 CLI 工具
```bash
# 诊断项目
venus diagnose
# 健康检查
venus doctor
# 查看帮助
venus --help
venus <command> --help
```
### 查看日志
```bash
# 查看构建日志
pnpm build --filter=@venus/my-app
# 查看详细日志
pnpm dev --filter=@venus/my-app --debug
# 查看错误日志
cat logs/*.log
```
### 查看文档
- [CLI 使用指南](./cli-usage.md)
- [配置指南](./configuration.md)
- [Monorepo 架构](./monorepo.md)
- [依赖管理](./dependency.md)
### 联系支持
如果以上方案都无法解决您的问题,请:
1. 收集错误信息和日志
2. 运行 `venus doctor` 获取环境信息
3. 在项目仓库提 Issue
4. 附上详细的复现步骤
## 常用调试命令
```bash
# 环境检查
venus doctor
# 项目诊断
venus diagnose
# 项目修复
venus fix --all
# 依赖检查
pnpm list
pnpm outdated
pnpm audit
# 代码检查
pnpm lint
pnpm typecheck
# 清理缓存
rm -rf node_modules .turbo .vite
pnpm install
```
\ No newline at end of file \ No newline at end of file
{ {
"name": "venus", "name": "venus",
"version": "0.0.1", "version": "0.1.0",
"private": true, "private": true,
"keywords": [ "keywords": [
"monorepo", "monorepo",
......
{ {
"name": "@venus/cli", "name": "@venus/cli",
"version": "0.0.1", "version": "0.1.0",
"description": "Venus CLI helpers", "description": "Venus CLI helpers",
"private": true, "private": true,
"type": "commonjs", "type": "commonjs",
......
import type { CreateOptions } from "../types";
import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { formatDiagnostics, runDiagnostics, type DiagnosticResult } from "../utils/diagnostics";
/**
* 诊断命令选项
*/
export interface DiagnoseOptions {
projectPath?: string;
verbose?: boolean;
fix?: boolean;
}
/**
* 运行项目诊断
*/
export async function runDiagnose(options: DiagnoseOptions = {}): Promise<void> {
const { projectPath = process.cwd(), verbose, fix } = options;
// 验证项目路径
if (!fs.existsSync(projectPath)) {
console.error(`✗ 项目路径不存在: ${projectPath}`);
process.exit(1);
}
const packageJsonPath = path.join(projectPath, "package.json");
if (!fs.existsSync(packageJsonPath)) {
console.error(`✗ 不是有效的 Venus 项目,package.json 不存在`);
process.exit(1);
}
// 显示诊断开始
console.log("\n🔍 开始诊断项目...\n");
try {
// 运行诊断
const result = runDiagnostics(projectPath);
// 显示结果
console.log(formatDiagnostics(result));
// 详细模式
if (verbose) {
console.log("\n📊 详细信息:");
console.log(`项目路径: ${result.projectPath}`);
console.log(`发现问题数: ${result.findings.length}`);
console.log(`错误数: ${result.findings.filter((f) => f.severity === "error").length}`);
console.log(`警告数: ${result.findings.filter((f) => f.severity === "warning").length}`);
}
// 询问是否修复
if (fix && !result.success) {
console.log("\n🔧 自动修复问题...");
try {
// 调用修复功能
const { runFix } = await import("./fix");
await runFix(projectPath, { dependencies: true, config: true });
// 重新诊断
console.log("\n🔍 重新诊断...");
const newResult = runDiagnostics(projectPath);
console.log(formatDiagnostics(newResult));
if (newResult.success) {
console.log("\n✅ 所有问题已修复!");
} else {
console.log("\n⚠️ 部分问题需要手动处理");
}
} catch (error) {
console.error(`\n✗ 自动修复失败: ${error instanceof Error ? error.message : String(error)}`);
console.log("请手动处理上述问题");
}
} else if (!result.success && !fix) {
console.log("\n💡 提示: 使用 'venus fix --all' 可以自动修复部分问题");
}
// 返回适当的退出码
process.exit(result.success ? 0 : 1);
} catch (error) {
console.error(`\n✗ 诊断失败: ${error instanceof Error ? error.message : String(error)}`);
if (verbose && error instanceof Error) {
console.error(error.stack);
}
process.exit(1);
}
}
/**
* 运行依赖检查
*/
export function runDependencyCheck(projectPath: string): void {
console.log("🔍 检查依赖...");
const packageJsonPath = path.join(projectPath, "package.json");
if (!fs.existsSync(packageJsonPath)) {
console.error("✗ package.json 不存在");
return;
}
try {
// 检查依赖是否正确安装
const nodeModulesPath = path.join(projectPath, "node_modules");
if (!fs.existsSync(nodeModulesPath)) {
console.error("✗ node_modules 不存在,请运行 'pnpm install'");
return;
}
// 检查常见依赖
const commonDeps = ["react", "vue", "typescript", "vite", "eslint"];
for (const dep of commonDeps) {
const depPath = path.join(nodeModulesPath, dep);
if (fs.existsSync(depPath)) {
const stats = fs.lstatSync(depPath);
if (stats.isSymbolicLink()) {
console.log(`✓ ${dep}: 软链接`);
} else {
console.warn(`⚠️ ${dep}: 完整副本`);
}
}
}
console.log("\n💡 如需修复依赖问题,运行: venus fix --dependencies");
} catch (error) {
console.error(`✗ 依赖检查失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* 运行配置检查
*/
export function runConfigCheck(projectPath: string): void {
console.log("🔍 检查配置...");
const configFiles = [
"package.json",
"tsconfig.json",
"vite.config.ts",
".eslintrc.js",
".prettierrc",
];
let missingFiles = 0;
let existingFiles = 0;
for (const configFile of configFiles) {
const configPath = path.join(projectPath, configFile);
if (fs.existsSync(configPath)) {
console.log(`✓ ${configFile}`);
existingFiles++;
} else {
console.log(`✗ ${configFile} (缺失)`);
missingFiles++;
}
}
console.log(`\n📊 配置文件: ${existingFiles} 个存在, ${missingFiles} 个缺失`);
if (missingFiles > 0) {
console.log("💡 建议补充缺失的配置文件");
}
}
/**
* 运行环境检查
*/
export function runEnvironmentCheck(): void {
console.log("🔍 检查开发环境...\n");
// Node.js 版本
const nodeVersion = process.version;
const nodeRequired = ">=20.10.0";
const nodeVersionOk = nodeVersion >= "v20.10.0";
console.log(`Node.js: ${nodeVersion} ${nodeVersionOk ? "✓" : "✗"} (需要 ${nodeRequired})`);
// pnpm 版本
try {
const pnpmVersion = child_process
.execSync("pnpm --version", { encoding: "utf8" })
.trim();
const pnpmRequired = ">=9.12.0";
// 简化的版本比较
const pnpmVersionOk = pnpmVersion >= "9.12.0";
console.log(`pnpm: ${pnpmVersion} ${pnpmVersionOk ? "✓" : "✗"} (需要 ${pnpmRequired})`);
} catch {
console.log("pnpm: ✗ (未安装或无法获取版本)");
}
// Git
try {
child_process.execSync("git --version", { encoding: "utf8", stdio: ["ignore"] });
console.log("Git: ✓");
} catch {
console.log("Git: ✗ (未安装)");
}
// 检查当前目录
const cwd = process.cwd();
const packageJsonPath = path.join(cwd, "package.json");
if (fs.existsSync(packageJsonPath)) {
console.log(`当前目录: ✓ (Venus 项目)`);
} else {
console.log(`当前目录: ✗ (不是 Venus 项目)`);
}
console.log("\n💡 如需修复环境问题,请按照上述提示操作");
}
\ No newline at end of file \ No newline at end of file
import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
/**
* 健康检查结果
*/
export interface HealthCheckResult {
isHealthy: boolean;
checks: HealthCheck[];
summary: string;
}
/**
* 单个健康检查项
*/
export interface HealthCheck {
name: string;
status: "pass" | "fail" | "warn";
message: string;
details?: string;
suggestion?: string;
}
/**
* 运行健康检查
*/
export async function runDoctor(): Promise<void> {
console.log("🏥 Venus 环境健康检查\n");
const checks = await performHealthChecks();
// 显示检查结果
displayHealthChecks(checks);
// 生成总结
const summary = generateSummary(checks);
console.log(`\n${summary}`);
// 返回适当的退出码
const hasFailures = checks.some((check) => check.status === "fail");
process.exit(hasFailures ? 1 : 0);
}
/**
* 执行所有健康检查
*/
async function performHealthChecks(): Promise<HealthCheck[]> {
const checks: HealthCheck[] = [];
// 1. Node.js 版本检查
checks.push(checkNodeVersion());
// 2. pnpm 版本检查
checks.push(checkPnpmVersion());
// 3. Git 检查
checks.push(checkGit());
// 4. workspace 配置检查
checks.push(checkWorkspaceConfig());
// 5. 依赖安装状态检查
checks.push(checkDependencyInstallation());
// 6. 配置文件检查
checks.push(checkConfigFiles());
// 7. 磁盘空间检查
checks.push(checkDiskSpace());
return checks;
}
/**
* 检查 Node.js 版本
*/
function checkNodeVersion(): HealthCheck {
const currentVersion = process.version;
const requiredVersion = ">=20.10.0";
try {
const isValid = currentVersion >= "v20.10.0";
return {
name: "Node.js",
status: isValid ? "pass" : "fail",
message: `Node.js 版本: ${currentVersion}`,
details: `要求: ${requiredVersion}`,
suggestion: isValid
? undefined
: "请使用 Volta 或 nvm 升级 Node.js 版本",
};
} catch {
return {
name: "Node.js",
status: "fail",
message: "无法获取 Node.js 版本",
suggestion: "请确认 Node.js 已正确安装",
};
}
}
/**
* 检查 pnpm 版本
*/
function checkPnpmVersion(): HealthCheck {
const requiredVersion = ">=9.12.0";
try {
const version = child_process.execSync("pnpm --version", {
encoding: "utf8",
stdio: ["ignore"],
}).trim();
// 简化的版本比较
const isValid = version >= "9.12.0";
return {
name: "pnpm",
status: isValid ? "pass" : "fail",
message: `pnpm 版本: ${version}`,
details: `要求: ${requiredVersion}`,
suggestion: isValid
? undefined
: "请运行: pnpm add -g pnpm@latest",
};
} catch {
return {
name: "pnpm",
status: "fail",
message: "pnpm 未安装或无法获取版本",
suggestion: "请运行: npm install -g pnpm",
};
}
}
/**
* 检查 Git
*/
function checkGit(): HealthCheck {
try {
const version = child_process.execSync("git --version", {
encoding: "utf8",
stdio: ["ignore"],
}).trim();
// 检查是否在 Git 仓库中
const isRepo = fs.existsSync(".git");
if (!isRepo) {
return {
name: "Git",
status: "warn",
message: `Git 已安装 (${version})`,
details: "但当前目录不是 Git 仓库",
suggestion: "请运行: git init",
};
}
return {
name: "Git",
status: "pass",
message: `Git 已安装 (${version})`,
details: "当前目录是 Git 仓库",
};
} catch {
return {
name: "Git",
status: "fail",
message: "Git 未安装",
suggestion: "请访问 https://git-scm.com/downloads 安装 Git",
};
}
}
/**
* 检查 workspace 配置
*/
function checkWorkspaceConfig(): HealthCheck {
const workspaceConfig = "pnpm-workspace.yaml";
if (fs.existsSync(workspaceConfig)) {
try {
const content = fs.readFileSync(workspaceConfig, "utf8");
const hasPackages = content.includes("packages:");
if (!hasPackages) {
return {
name: "Workspace 配置",
status: "warn",
message: "workspace 配置文件存在但缺少 packages 定义",
details: workspaceConfig,
suggestion: "请在 pnpm-workspace.yaml 中添加 packages 定义",
};
}
return {
name: "Workspace 配置",
status: "pass",
message: "workspace 配置文件存在且有效",
details: workspaceConfig,
};
} catch {
return {
name: "Workspace 配置",
status: "fail",
message: "workspace 配置文件格式错误",
suggestion: "请检查 pnpm-workspace.yaml 的语法",
};
}
} else {
return {
name: "Workspace 配置",
status: "warn",
message: "未找到 workspace 配置文件",
details: "独立项目不需要 workspace 配置",
suggestion: "如果需要在 monorepo 中开发,请创建 pnpm-workspace.yaml",
};
}
}
/**
* 检查依赖安装状态
*/
function checkDependencyInstallation(): HealthCheck {
const nodeModulesPath = "node_modules";
const lockFilePath = "pnpm-lock.yaml";
let status: "pass" | "fail" | "warn" = "pass";
let message = "";
if (!fs.existsSync(nodeModulesPath)) {
status = "fail";
message = "依赖未安装 (node_modules 不存在)";
} else if (!fs.existsSync(lockFilePath)) {
status = "fail";
message = "lock 文件缺失 (pnpm-lock.yaml 不存在)";
} else {
// 检查关键依赖
const criticalDeps = ["typescript", "vite", "eslint"];
const missingDeps = criticalDeps.filter((dep) => {
const depPath = path.join(nodeModulesPath, dep);
return !fs.existsSync(depPath);
});
if (missingDeps.length > 0) {
status = "fail";
message = `关键依赖缺失: ${missingDeps.join(", ")}`;
} else {
message = "依赖已正确安装";
}
}
return {
name: "依赖安装",
status,
message,
suggestion: status !== "pass" ? "请运行: pnpm install" : undefined,
};
}
/**
* 检查配置文件
*/
function checkConfigFiles(): HealthCheck {
const configFiles = [
{ file: "package.json", required: true },
{ file: "tsconfig.json", required: false },
{ file: ".eslintrc.js", required: false },
{ file: ".prettierrc", required: false },
];
const missingRequired: string[] = [];
const missingOptional: string[] = [];
for (const config of configFiles) {
if (!fs.existsSync(config.file)) {
if (config.required) {
missingRequired.push(config.file);
} else {
missingOptional.push(config.file);
}
}
}
if (missingRequired.length > 0) {
return {
name: "配置文件",
status: "fail",
message: `缺少必需配置: ${missingRequired.join(", ")}`,
suggestion: "请确保项目包含必要的配置文件",
};
}
if (missingOptional.length > 0) {
return {
name: "配置文件",
status: "warn",
message: `缺少可选配置: ${missingOptional.join(", ")}`,
suggestion: "建议添加这些配置以获得更好的开发体验",
};
}
return {
name: "配置文件",
status: "pass",
message: "所有配置文件齐全",
};
}
/**
* 检查磁盘空间
*/
function checkDiskSpace(): HealthCheck {
try {
const stats = fs.statSync(".");
// 简化的磁盘空间检查
// 在 Windows 上可以使用 wmic,在 Linux/Mac 上可以使用 df
return {
name: "磁盘空间",
status: "pass",
message: "磁盘空间检查通过",
details: "磁盘空间充足",
};
} catch {
return {
name: "磁盘空间",
status: "warn",
message: "无法检查磁盘空间",
suggestion: "请确保有足够的磁盘空间用于开发",
};
}
}
/**
* 显示健康检查结果
*/
function displayHealthChecks(checks: HealthCheck[]): void {
for (const check of checks) {
const icon = check.status === "pass" ? "✓" : check.status === "fail" ? "✗" : "⚠️";
const statusColor = check.status === "pass" ? "green" : check.status === "fail" ? "red" : "yellow";
console.log(`${icon} ${check.name}: ${check.message}`);
if (check.details) {
console.log(` 详情: ${check.details}`);
}
if (check.suggestion) {
console.log(` 建议: ${check.suggestion}`);
}
console.log("");
}
}
/**
* 生成总结
*/
function generateSummary(checks: HealthCheck[]): string {
const passed = checks.filter((c) => c.status === "pass").length;
const failed = checks.filter((c) => c.status === "fail").length;
const warnings = checks.filter((c) => c.status === "warn").length;
if (failed === 0 && warnings === 0) {
return "✅ 环境健康!所有检查都通过了。";
}
let summary = "";
if (failed > 0) {
summary += `❌ 发现 ${failed} 个严重问题`;
}
if (warnings > 0) {
if (summary) {
summary += `, `;
}
summary += `⚠️ 发现 ${warnings} 个警告`;
}
summary += "\n\n💡 建议优先处理严重问题,确保开发环境正常。";
return summary;
}
/**
* 快速检查(仅检查关键项)
*/
export function quickCheck(): boolean {
console.log("⚡ 快速检查...\n");
const criticalChecks = [checkNodeVersion(), checkPnpmVersion(), checkDependencyInstallation()];
const hasFailures = criticalChecks.some((check) => check.status === "fail");
displayHealthChecks(criticalChecks);
return !hasFailures;
}
\ No newline at end of file \ No newline at end of file
import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { runDiagnostics, type DiagnosticResult } from "../utils/diagnostics";
import { findWorkspaceRoot } from "../utils/workspace";
/**
* 修复命令选项
*/
export interface FixOptions {
dependencies?: boolean;
config?: boolean;
all?: boolean;
force?: boolean;
dryRun?: boolean;
}
/**
* 运行项目修复
*/
export async function runFix(projectPath: string, options: FixOptions = {}): Promise<void> {
const { dependencies, config, all, force, dryRun } = options;
// 验证项目路径
if (!fs.existsSync(projectPath)) {
console.error(`✗ 项目路径不存在: ${projectPath}`);
process.exit(1);
}
const packageJsonPath = path.join(projectPath, "package.json");
if (!fs.existsSync(packageJsonPath)) {
console.error(`✗ 不是有效的 Venus 项目,package.json 不存在`);
process.exit(1);
}
// 显示修复开始
console.log(`\n🔧 开始修复项目: ${projectPath}\n`);
if (dryRun) {
console.log("📋 模拟模式 (dry-run),不会实际执行修复\n");
}
try {
// 先诊断问题
console.log("🔍 诊断项目问题...");
const diagnosticResult = runDiagnostics(projectPath);
console.log(`发现 ${diagnosticResult.findings.filter((f) => f.severity !== "info").length} 个问题\n`);
// 确定修复范围
const fixDependencies = dependencies || all;
const fixConfig = config || all;
if (!fixDependencies && !fixConfig) {
console.log("请指定修复内容:--dependencies, --config, 或 --all");
console.log("使用 --help 查看帮助");
process.exit(1);
}
// 执行修复
let fixedCount = 0;
let skippedCount = 0;
// 修复依赖问题
if (fixDependencies) {
console.log("📦 修复依赖问题...");
const dependencyFixResult = await fixDependenciesProblem(
projectPath,
dryRun,
force,
);
if (dependencyFixResult) {
fixedCount++;
} else {
skippedCount++;
}
}
// 修复配置问题
if (fixConfig) {
console.log("\n⚙️ 修复配置问题...");
const configFixResult = await fixConfigProblem(projectPath, dryRun, force);
if (configFixResult) {
fixedCount++;
} else {
skippedCount++;
}
}
// 显示修复结果
console.log("\n📊 修复结果:");
console.log(` - 已修复: ${fixedCount} 项`);
console.log(` - 跳过: ${skippedCount} 项`);
if (!dryRun) {
console.log("\n💡 建议运行 'venus doctor' 验证修复结果");
}
process.exit(0);
} catch (error) {
console.error(`\n✗ 修复失败: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
}
/**
* 修复依赖问题
*/
async function fixDependenciesProblem(
projectPath: string,
dryRun: boolean,
force: boolean,
): Promise<boolean> {
const workspaceRoot = findWorkspaceRoot(projectPath);
const nodeModulesPath = path.join(projectPath, "node_modules");
// 检查是否需要修复
let needsFix = false;
if (workspaceRoot) {
console.log(` ✓ 检测到 workspace: ${workspaceRoot}`);
if (fs.existsSync(nodeModulesPath)) {
console.log(` ✓ node_modules 存在`);
// 检查是否有完整的依赖副本
const reactPath = path.join(nodeModulesPath, "react");
if (fs.existsSync(reactPath)) {
try {
const stats = fs.lstatSync(reactPath);
if (!stats.isSymbolicLink()) {
console.log(` ⚠️ 检测到完整依赖副本而非软链接`);
needsFix = true;
} else {
console.log(` ✓ 依赖已是软链接,无需修复`);
}
} catch {
needsFix = true;
}
}
} else {
console.log(` ✓ node_modules 不存在,将创建软链接`);
needsFix = true;
}
} else {
console.log(` ℹ️ 项目不在 workspace 中,无需特殊处理`);
return false;
}
if (!needsFix && !force) {
console.log(` ✓ 依赖配置正常,无需修复`);
return false;
}
// 执行修复
if (dryRun) {
console.log(` [模拟] 将删除 ${nodeModulesPath}`);
console.log(` [模拟] 将在 workspace 根目录执行 pnpm install`);
return true;
}
try {
// 删除子项目 node_modules
if (fs.existsSync(nodeModulesPath)) {
console.log(` 🗑️ 删除 ${nodeModulesPath}`);
fs.rmSync(nodeModulesPath, { recursive: true, force: true });
}
// 在 workspace 根目录重新安装
console.log(` 📦 在 workspace 根目录重新安装依赖`);
console.log(` 📍 安装目录: ${workspaceRoot}`);
child_process.execSync("pnpm install", {
cwd: workspaceRoot,
stdio: "inherit",
});
console.log(` ✅ 依赖修复完成`);
return true;
} catch (error) {
console.error(` ❌ 依赖修复失败: ${error instanceof Error ? error.message : String(error)}`);
throw error;
}
}
/**
* 修复配置问题
*/
async function fixConfigProblem(
projectPath: string,
dryRun: boolean,
force: boolean,
): Promise<boolean> {
const configFiles = [
{ file: "tsconfig.json", template: "tsconfig" },
{ file: ".eslintrc.js", template: "eslint" },
{ file: ".prettierrc", template: "prettier" },
];
let needsFix = false;
let fixedFiles = 0;
for (const config of configFiles) {
const configPath = path.join(projectPath, config.file);
if (!fs.existsSync(configPath)) {
console.log(` ℹ️ 缺少配置: ${config.file}`);
needsFix = true;
}
}
if (!needsFix && !force) {
console.log(` ✓ 配置文件齐全,无需修复`);
return false;
}
if (dryRun) {
console.log(` [模拟] 将创建缺失的配置文件`);
return true;
}
try {
// 创建基础配置
for (const config of configFiles) {
const configPath = path.join(projectPath, config.file);
if (!fs.existsSync(configPath)) {
console.log(` 📝 创建配置: ${config.file}`);
// 根据配置类型创建基础配置
if (config.file === ".eslintrc.js") {
fs.writeFileSync(
configPath,
`module.exports = require('@venus/eslint-config')\n`,
);
fixedFiles++;
} else if (config.file === ".prettierrc") {
fs.writeFileSync(configPath, JSON.stringify(require("@venus/prettier-config"), null, 2) + "\n");
fixedFiles++;
} else if (config.file === "tsconfig.json") {
fs.writeFileSync(
configPath,
JSON.stringify(
{
extends: "@venus/tsconfig/base.json",
compilerOptions: {
baseUrl: ".",
paths: {
"@/*": ["./src/*"],
},
},
include: ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
},
null,
2,
) + "\n",
);
fixedFiles++;
}
}
}
if (fixedFiles > 0) {
console.log(` ✅ 配置修复完成 (${fixedFiles} 个文件)`);
return true;
} else {
console.log(` ℹ️ 配置已经是最新的`);
return false;
}
} catch (error) {
console.error(` ❌ 配置修复失败: ${error instanceof Error ? error.message : String(error)}`);
throw error;
}
}
/**
* 快速修复常见问题
*/
export async function quickFix(projectPath: string, issueType: string): Promise<boolean> {
console.log(`\n🔧 快速修复: ${issueType}`);
try {
switch (issueType) {
case "dependencies":
return await fixDependenciesProblem(projectPath, false, true);
case "config":
return await fixConfigProblem(projectPath, false, true);
default:
console.error(`✗ 未知的修复类型: ${issueType}`);
return false;
}
} catch (error) {
console.error(`✗ 快速修复失败: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}
\ No newline at end of file \ No newline at end of file
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { analyzeProjectDependencies, findWorkspaceRoot } from "../utils/workspace";
/**
* 项目信息
*/
export interface ProjectInfo {
name: string;
version: string;
description?: string;
author?: string;
license?: string;
template?: string;
path: string;
workspaceRoot?: string;
inWorkspace: boolean;
dependencies: DependencyInfo;
devDependencies: DependencyInfo;
configs: ConfigInfo;
}
/**
* 依赖信息
*/
export interface DependencyInfo {
total: number;
catalogDeps: number;
regularDeps: number;
list?: string[];
}
/**
* 配置信息
*/
export interface ConfigInfo {
typeScript: boolean;
vite: boolean;
eslint: boolean;
prettier: boolean;
git: boolean;
workspace: boolean;
exists: string[];
missing: string[];
}
/**
* 获取项目信息
*/
export async function getProjectInfo(projectPath?: string): Promise<ProjectInfo> {
const cwd = projectPath || process.cwd();
const packageJsonPath = path.join(cwd, "package.json");
if (!fs.existsSync(packageJsonPath)) {
throw new Error(`不是有效的项目,package.json 不存在: ${packageJsonPath}`);
}
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
const workspaceRoot = findWorkspaceRoot(cwd);
const dependencyAnalysis = analyzeProjectDependencies(packageJsonPath);
// 分析配置文件
const configInfo = analyzeConfigFiles(cwd);
// 分析依赖
const deps = analyzeDependencies(packageJson, dependencyAnalysis);
// 检测模板类型
const template = detectTemplate(packageJson, configInfo);
return {
name: packageJson.name || "unknown",
version: packageJson.version || "0.0.0",
description: packageJson.description,
author: packageJson.author ? String(packageJson.author) : undefined,
license: packageJson.license,
template,
path: cwd,
workspaceRoot: workspaceRoot || undefined,
inWorkspace: !!workspaceRoot,
dependencies: deps.dependencies,
devDependencies: deps.devDependencies,
configs: configInfo,
};
}
/**
* 分析配置文件
*/
function analyzeConfigFiles(projectPath: string): ConfigInfo {
const configFiles = {
typescript: ["tsconfig.json", "tsconfig.ts"],
vite: ["vite.config.ts", "vite.config.mjs", "vite.config.js"],
eslint: [".eslintrc.js", "eslint.config.mjs", ".eslintrc.cjs"],
prettier: [".prettierrc", "prettier.config.mjs", ".prettierrc.json"],
git: [".git"],
workspace: ["pnpm-workspace.yaml"],
};
const exists: string[] = [];
const missing: string[] = [];
// 检查配置文件
for (const [configType, files] of Object.entries(configFiles)) {
const hasFile = files.some((file) => fs.existsSync(path.join(projectPath, file)));
if (hasFile) {
exists.push(configType);
} else {
missing.push(configType);
}
}
return {
typeScript: exists.includes("typescript"),
vite: exists.includes("vite"),
eslint: exists.includes("eslint"),
prettier: exists.includes("prettier"),
git: exists.includes("git"),
workspace: exists.includes("workspace"),
exists,
missing,
};
}
/**
* 分析依赖
*/
function analyzeDependencies(
packageJson: any,
dependencyAnalysis: { hasCatalogDeps: boolean; hasRegularDeps: boolean },
): { dependencies: DependencyInfo; devDependencies: DependencyInfo } {
const countDeps = (deps: Record<string, string>) => {
const list = Object.keys(deps);
const catalogCount = Object.values(deps).filter((dep) => dep === "catalog:").length;
return {
total: list.length,
catalogDeps: catalogCount,
regularDeps: list.length - catalogCount,
list,
};
};
const dependencies = countDeps(packageJson.dependencies || {});
const devDependencies = countDeps(packageJson.devDependencies || {});
return { dependencies, devDependencies };
}
/**
* 检测模板类型
*/
function detectTemplate(packageJson: any, configInfo: ConfigInfo): string {
const deps = packageJson.dependencies || {};
const devDeps = packageJson.devDependencies || {};
// 检查是否是 React 项目
if (deps.react || deps["react-dom"]) {
if (deps.antd) {
return "React + Ant Design";
}
return "React";
}
// 检查是否是 Vue 项目
if (deps.vue) {
if (deps["element-plus"]) {
return "Vue + Element Plus";
}
if (deps["ant-design-vue"]) {
return "Vue + Ant Design Vue";
}
return "Vue";
}
// 检查其他特征
if (deps.uniapp) {
return "UniApp";
}
return "未知";
}
/**
* 格式化项目信息
*/
export function formatProjectInfo(info: ProjectInfo): string {
const lines: string[] = [];
lines.push("📋 项目信息\n");
lines.push(`名称: ${info.name}`);
lines.push(`版本: ${info.version}`);
if (info.description) {
lines.push(`描述: ${info.description}`);
}
if (info.author) {
lines.push(`作者: ${info.author}`);
}
if (info.license) {
lines.push(`许可证: ${info.license}`);
}
if (info.template) {
lines.push(`模板: ${info.template}`);
}
lines.push(`路径: ${info.path}`);
lines.push(`Workspace: ${info.inWorkspace ? "是" : "否"}`);
if (info.workspaceRoot) {
lines.push(`Workspace 根目录: ${info.workspaceRoot}`);
}
// 依赖信息
lines.push("\n📦 依赖信息");
lines.push(`生产依赖: ${info.dependencies.total}`);
lines.push(` - Catalog: ${info.dependencies.catalogDeps}`);
lines.push(` - 常规: ${info.dependencies.regularDeps}`);
lines.push(`开发依赖: ${info.devDependencies.total}`);
lines.push(` - Catalog: ${info.devDependencies.catalogDeps}`);
lines.push(` - 常规: ${info.devDependencies.regularDeps}`);
// 配置信息
lines.push("\n⚙️ 配置信息");
lines.push(`TypeScript: ${info.configs.typeScript ? "✓" : "✗"}`);
lines.push(`Vite: ${info.configs.vite ? "✓" : "✗"}`);
lines.push(`ESLint: ${info.configs.eslint ? "✓" : "✗"}`);
lines.push(`Prettier: ${info.configs.prettier ? "✓" : "✗"}`);
lines.push(`Git: ${info.configs.git ? "✓" : "✗"}`);
lines.push(`Workspace: ${info.configs.workspace ? "✓" : "✗"}`);
return lines.join("\n");
}
/**
* 显示依赖列表
*/
export function showDependencyList(info: ProjectInfo): string {
const lines: string[] = [];
lines.push("📦 依赖详情\n");
if (info.dependencies.list && info.dependencies.list.length > 0) {
lines.push("生产依赖:");
info.dependencies.list.forEach((dep) => {
lines.push(` - ${dep}`);
});
}
if (info.devDependencies.list && info.devDependencies.list.length > 0) {
lines.push("\n开发依赖:");
info.devDependencies.list.forEach((dep) => {
lines.push(` - ${dep}`);
});
}
return lines.join("\n");
}
/**
* 比较两个项目的依赖差异
*/
export function compareDependencies(
projectA: ProjectInfo,
projectB: ProjectInfo,
): string {
const lines: string[] = [];
lines.push("📊 依赖对比\n");
lines.push(`项目 A: ${projectA.name}`);
lines.push(`项目 B: ${projectB.name}`);
// 对比生产依赖
const depsA = new Set(projectA.dependencies.list || []);
const depsB = new Set(projectB.dependencies.list || []);
const onlyInA = [...depsA].filter((dep) => !depsB.has(dep));
const onlyInB = [...depsB].filter((dep) => !depsA.has(dep));
const common = [...depsA].filter((dep) => depsB.has(dep));
lines.push(`\n仅在项目 A 中 (${onlyInA.length}):`);
if (onlyInA.length > 0) {
onlyInA.forEach((dep) => lines.push(` - ${dep}`));
} else {
lines.push(" 无");
}
lines.push(`\n仅在项目 B 中 (${onlyInB.length}):`);
if (onlyInB.length > 0) {
onlyInB.forEach((dep) => lines.push(` - ${dep}`));
} else {
lines.push(" 无");
}
lines.push(`\n共同依赖 (${common.length}):`);
if (common.length > 0) {
common.forEach((dep) => lines.push(` - ${dep}`));
} else {
lines.push(" 无");
}
return lines.join("\n");
}
/**
* 生成 JSON 格式的项目信息
*/
export function toJson(info: ProjectInfo): string {
return JSON.stringify(
{
name: info.name,
version: info.version,
description: info.description,
template: info.template,
dependencies: {
production: info.dependencies.total,
development: info.devDependencies.total,
},
configs: info.configs.exists,
inWorkspace: info.inWorkspace,
},
null,
2,
);
}
/**
* 验证项目配置
*/
export function validateProjectConfig(info: ProjectInfo): boolean {
// 检查必需配置
const requiredConfigs = ["eslint", "prettier"];
const missingRequired = requiredConfigs.filter((config) => !info.configs.exists.includes(config));
if (missingRequired.length > 0) {
console.log(`❌ 缺少必需配置: ${missingRequired.join(", ")}`);
return false;
}
// 检查依赖
if (info.dependencies.total === 0 && info.devDependencies.total === 0) {
console.log("❌ 项目没有定义任何依赖");
return false;
}
// 检查 TypeScript(推荐)
if (!info.configs.typeScript) {
console.log("⚠️ 建议启用 TypeScript");
}
// 检查 Git(推荐)
if (!info.configs.git) {
console.log("⚠️ 建议初始化 Git");
}
return true;
}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!