import Add from "/snippets/cli/add.mdx";
要添加特定的包:
bash
bun add preact要指定版本、版本范围或标签:
bash
bun add zod@3.20.0
bun add zod@^3.0.0
bun add zod@latest--dev
NOTE
**别名** — `--development`、`-d`、`-D`要将包添加为开发依赖("devDependencies"):
bash
bun add --dev @types/react
bun add -d @types/react--optional
要将包添加为可选依赖("optionalDependencies"):
bash
bun add --optional lodash--peer
要将包添加为 peer 依赖("peerDependencies"):
bash
bun add --peer @types/bun--exact
NOTE
**别名** — `-E`要添加包并固定到解析的版本,请使用 --exact。这将解析包的版本,并将其以精确版本号添加到你的 package.json,而不是版本范围。
bash
bun add react --exact
bun add react -E这将在你的 package.json 中添加以下内容:
json
{
"dependencies": {
// 不使用 --exact
"react": "^18.2.0", // 这匹配 >= 18.2.0 < 19.0.0
// 使用 --exact
"react": "18.2.0" // 这仅精确匹配 18.2.0
}
}要查看此命令的完整选项列表:
bash
bun add --help--global
NOTE
**注意** — 这不会修改当前项目文件夹的 package.json。**别名** - `bun add --global`、`bun add -g`、`bun install --global` 和 `bun install -g`要全局安装包,请使用 -g/--global 标志。这不会修改当前项目的 package.json。通常这用于安装命令行工具。
bash
bun add --global cowsay # 或 `bun add -g cowsay`
cowsay "Bun!"txt
______
< Bun! >
------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||配置全局安装行为
toml
[install]
# `bun add --global` 安装包的位置
globalDir = "~/.bun/install/global"
# 全局安装的包二进制文件链接的位置
globalBinDir = "~/.bun/bin"受信任的依赖
与其他 npm 客户端不同,Bun 不为已安装的依赖执行任意的生命周期脚本,例如 postinstall。这些脚本代表潜在的安全风险,因为它们可以在你的机器上执行任意代码。
要告诉 Bun 允许特定包的生命周期脚本,请将包添加到 package.json 中的 trustedDependencies。
json
{
"name": "my-app",
"version": "1.0.0",
"trustedDependencies": ["my-trusted-package"]
}Bun 读取此字段并将为 my-trusted-package 运行生命周期脚本。
Git 依赖
要从公共或私有 git 仓库添加依赖:
bash
bun add git@github.com:moment/moment.gitNOTE
要安装私有仓库,你的系统需要适当的 SSH 凭据来访问仓库。Bun 支持各种协议,包括 github、git、git+ssh、git+https 等。
json
{
"dependencies": {
"dayjs": "git+https://github.com/iamkun/dayjs.git",
"lodash": "git+ssh://github.com/lodash/lodash.git#4.17.21",
"moment": "git@github.com:moment/moment.git",
"zod": "github:colinhacks/zod"
}
}Tarball 依赖
包名称可以对应于公开托管的 .tgz 文件。在安装期间,Bun 将从指定的 tarball URL 下载并安装包,而不是从包注册表。
sh
bun add zod@https://registry.npmjs.org/zod/-/zod-3.21.4.tgz这将在你的 package.json 中添加以下行:
json
{
"dependencies": {
"zod": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz"
}
}