> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 workspaces 配置 monorepo

Bun 的包管理器支持 npm 的 `"workspaces"`。这允许你将代码库拆分成多个独立的“包”，它们位于同一个仓库中，可以相互依赖，并且（在可能的情况下）共享一个 `node_modules` 目录。

克隆[这个示例项目](https://github.com/colinhacks/bun-workspaces)来尝试使用 workspaces。

***

根目录的 `package.json` 不应包含任何 `"dependencies"`、`"devDependencies"` 等。每个独立的包都应该是自包含的，并声明自己的依赖。同样，通常会声明 `"private": true`，以避免意外将根包发布到 `npm` 上。

```json package.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "name": "my-monorepo",
  "private": true,
  "workspaces": ["packages/*"]
}
```

***

通常会将所有包放在 `packages` 目录下。`package.json` 中的 `"workspaces"` 字段支持通配符模式，因此你可以使用 `packages/*` 来表示 `packages` 下的每个子目录都应被视为独立的 *package*（也称为 workspace）。

```txt File Tree icon="folder-tree" theme={"theme":{"light":"github-light","dark":"dracula"}}
.
├── package.json
├── node_modules
└── packages
    ├── stuff-a
    │   └── package.json
    └── stuff-b
        └── package.json
```

***

要在 workspaces 之间添加依赖，使用 `"workspace:*"` 语法。这里我们把 `stuff-a` 添加为 `stuff-b` 的依赖。

```json packages/stuff-b/package.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "name": "stuff-b",
  "dependencies": {
    "stuff-a": "workspace:*" // [!code ++]
  }
}
```

***

添加后，从项目根目录运行 `bun install` 来安装所有 workspaces 的依赖。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun install
```

***

要向特定的 workspace 添加 npm 依赖，`cd` 到相应的目录，并像往常一样运行 `bun add` 命令。Bun 会检测到你处于 workspace 中，并根据需要提升（hoist）该依赖。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
cd packages/stuff-a
bun add zod
```

***

完整的 Bun 包管理器文档，请参见 [文档 > 包管理器](/pm/cli/install)。
