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"
}
}