Files
opencode-config/skills/bun-catalog-package/SKILL.md
imbytecat 7aeebb2dcd feat: 添加 Bun monorepo catalog 依赖管理操作指南
- 添加 Bun monorepo 项目中通过 catalog 统一管理依赖包的完整操作指南,明确规范根目录配置与子包引用流程,解决子包无法直接使用 catalog 的限制问题。
2026-01-22 11:15:43 +08:00

160 lines
3.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
name: bun-catalog-package
description: Bun 包管理器中使用 catalog 功能添加依赖包的标准流程指南。当用户需要在 Bun monorepo 项目中使用 catalog 功能添加或管理依赖包时使用此技能。适用于解决 Bun 不支持在子包直接安装 catalog 依赖的限制问题。
---
# Bun Catalog 包管理流程
## 问题背景
Bun 包管理器目前**不支持**在子包workspace中直接安装并自动添加到 catalog 的包。如果在子包目录执行 `bun add <包名>`,包会直接添加到子包的 `package.json`,而不会使用 catalog 引用。
## 标准操作流程
### 1. 查询包的最新版本
```bash
bun info <包名>
```
**示例**:
```bash
bun info zod
# 输出示例:
# zod@4.0.0 - TypeScript-first schema validation
```
从输出中获取包名和最新版本号(例如 `zod@4.0.0`)。
### 2. 添加到根 package.json 的 catalog
在项目根目录的 `package.json` 中找到 `catalog` 字段,手动添加包及其版本:
```json
{
"workspaces": ["apps/*", "packages/*"],
"catalog": {
"react": "^18.3.1",
"typescript": "^5.0.0",
"zod": "^4.0.0" // 新增的包
}
}
```
**注意事项**:
- 使用 `^` 前缀表示自动更新小版本(推荐)
- 也可以使用精确版本号(不加 `^`)锁定版本
### 3. 在子包中引用 catalog
在需要使用该包的子包(如 `apps/api/package.json`)中,添加 catalog 引用:
```json
{
"name": "@my-project/api",
"dependencies": {
"hono": "catalog:",
"zod": "catalog:" // 引用 catalog 中的 zod
}
}
```
**格式说明**:
- 使用 `"包名": "catalog:"` 格式
- **不需要**指定版本号,会自动使用根 `package.json` 中 catalog 定义的版本
### 4. 安装依赖
在项目根目录执行:
```bash
bun install
```
Bun 会:
1. 解析 catalog 中定义的版本
2. 将包安装到子包的 `node_modules`
3. 保持子包 `package.json` 中的 `catalog:` 引用不变
## 完整示例
假设要在 `apps/api` 中添加 `@hono/zod-validator` 包:
```bash
# 步骤 1: 查询版本
bun info @hono/zod-validator
# 输出: @hono/zod-validator@0.4.1
# 步骤 2: 编辑根 package.json
# {
# "catalog": {
# "@hono/zod-validator": "^0.4.1"
# }
# }
# 步骤 3: 编辑 apps/api/package.json
# {
# "dependencies": {
# "@hono/zod-validator": "catalog:"
# }
# }
# 步骤 4: 安装
bun install
```
## 优势
使用 catalog 管理依赖的好处:
1. **版本统一**: 所有子包使用相同版本,避免版本冲突
2. **集中管理**: 在根 `package.json` 一处更新版本
3. **减少重复**: 子包中只需写 `catalog:`,无需重复版本号
4. **自动同步**: 更新 catalog 版本后,所有引用自动生效
## 注意事项
- ✅ 始终在**根目录**执行 `bun install`
- ✅ catalog 定义在**根 `package.json`**
- ✅ 子包中使用 `"catalog:"` 引用(注意有冒号)
- ❌ 不要在子包目录直接 `bun add <包名>`(会绕过 catalog
- ❌ 不要在子包 `package.json` 中写具体版本号(如 `"zod": "^4.0.0"`
## 疑难排查
### 问题:子包中显示 "catalog: 未找到"
**原因**: 根 `package.json``catalog` 字段中没有该包
**解决**: 检查根 `package.json`,确保包已添加到 `catalog` 对象中
### 问题:安装后版本不是最新的
**原因**: catalog 中定义的版本过旧
**解决**:
1. 运行 `bun info <包名>` 查看最新版本
2. 更新根 `package.json` 中 catalog 的版本号
3. 重新运行 `bun install`
## 相关命令速查
```bash
# 查询包信息(版本、描述等)
bun info <包名>
# 查看已安装包的版本
bun pm ls <包名>
# 更新所有依赖到 catalog 定义的版本
bun install
# 查看 catalog 配置
cat package.json | grep -A 20 "catalog"
```
---
**最后更新**: 2026-01-22
**适用版本**: Bun 1.0+