Skip to content

Bun 运行脚本

本章详细介绍 Bun 的脚本运行功能,包括运行文件、package.json 脚本、监听模式等特性。

运行 JavaScript/TypeScript 文件

基本运行

bash
# 运行 JavaScript
bun index.js

# 运行 TypeScript(无需编译)
bun index.ts

# 运行 JSX/TSX
bun app.jsx
bun app.tsx

使用 run 命令

bash
# 显式使用 run
bun run index.ts

# 等同于
bun index.ts

支持的文件类型

Bun 原生支持多种文件类型:

扩展名说明
.jsJavaScript
.tsTypeScript
.jsxJavaScript + JSX
.tsxTypeScript + JSX
.mjsES Module JavaScript
.mtsES Module TypeScript
.cjsCommonJS JavaScript
.ctsCommonJS TypeScript

示例

typescript
// greeting.tsx
interface Props {
  name: string;
}

function Greeting({ name }: Props) {
  return <div>你好, {name}!</div>;
}

console.log(Greeting({ name: "Bun" }));
bash
bun greeting.tsx

package.json 脚本

定义脚本

json
{
  "scripts": {
    "start": "bun src/index.ts",
    "dev": "bun --watch src/index.ts",
    "build": "bun build src/index.ts --outdir dist",
    "test": "bun test",
    "lint": "eslint src/**/*.ts",
    "format": "prettier --write src/**/*.ts",
    "typecheck": "tsc --noEmit",
    "clean": "rm -rf dist node_modules"
  }
}

运行脚本

bash
# 使用 run 命令
bun run start
bun run dev
bun run build

# start 脚本可省略 run
bun start

# 其他脚本也可省略 run
bun dev
bun test

传递参数

bash
# 向脚本传递参数
bun run build -- --minify

# 脚本定义
# "build": "bun build src/index.ts --outdir dist"
# 实际执行: bun build src/index.ts --outdir dist --minify

监听模式

自动重载

使用 --watch 监听文件变化并自动重新运行:

bash
bun --watch index.ts

index.ts 或其导入的文件发生变化时,Bun 会自动重新运行。

监听特定文件

bash
# 监听额外文件
bun --watch index.ts --watch-file ./config.json

热重载模式

对于 HTTP 服务器,使用 --hot 实现热重载:

bash
bun --hot server.ts
typescript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello!");
  },
});

// 支持热重载
export default server;

热重载的特点:

  • 保持连接不断开
  • 状态可以保留
  • --watch 更快

运行选项

常用选项

bash
# 指定入口
bun run --entry ./src/main.ts

# 设置环境变量
bun run --env-file .env.production index.ts

# 静默模式(减少输出)
bun run --silent index.ts

# 详细模式(更多输出)
bun run --verbose index.ts

调试选项

bash
# 启用调试器
bun --inspect index.ts

# 调试器并等待连接
bun --inspect-wait index.ts

# 指定调试端口
bun --inspect=127.0.0.1:9229 index.ts

内存和性能

bash
# 设置堆内存大小
bun --smol index.ts  # 使用更少内存

# 预加载脚本
bun --preload ./setup.ts index.ts

执行远程脚本

运行 URL

bash
# 运行远程脚本
bun run https://example.com/script.ts

运行 Gist

bash
# 运行 GitHub Gist
bun run https://gist.github.com/user/gist-id/raw/script.ts

执行系统命令

Shell 脚本

Bun 可以运行 package.json 中定义的 shell 命令:

json
{
  "scripts": {
    "clean": "rm -rf dist",
    "copy": "cp -r public dist/public",
    "setup": "mkdir -p dist && cp config.json dist/"
  }
}

使用 Bun Shell

typescript
// shell-script.ts
import { $ } from "bun";

// 运行 shell 命令
await $`echo "Hello from Bun Shell"`;

// 捕获输出
const result = await $`ls -la`.text();
console.log(result);

// 传递变量
const name = "Bun";
await $`echo "Hello ${name}"`;

// 管道操作
await $`cat file.txt | grep "pattern" | wc -l`;

运行 npm 包

使用 bunx

类似于 npx,可以运行 npm 包:

bash
# 运行已安装的包
bunx tsc --version

# 运行并下载包
bunx create-react-app my-app

# 指定版本
bunx typescript@5.0 --version

对比 npx

bash
# Bun 方式(更快)
bunx vite

# npm 方式
npx vite

多环境配置

环境变量文件

bash
# 加载不同环境配置
bun --env-file .env.development index.ts
bun --env-file .env.production index.ts

脚本中区分环境

json
{
  "scripts": {
    "start": "bun --env-file .env.production src/index.ts",
    "dev": "bun --env-file .env.development --watch src/index.ts",
    "staging": "bun --env-file .env.staging src/index.ts"
  }
}

生命周期脚本

pre 和 post 钩子

json
{
  "scripts": {
    "prebuild": "echo '开始构建...'",
    "build": "bun build src/index.ts --outdir dist",
    "postbuild": "echo '构建完成!'",
    
    "pretest": "bun run lint",
    "test": "bun test",
    "posttest": "echo '测试完成!'"
  }
}

运行 bun run build 会依次执行:

  1. prebuild
  2. build
  3. postbuild

并行运行脚本

使用 bun-shell

typescript
// parallel.ts
import { $ } from "bun";

// 并行运行多个命令
await Promise.all([
  $`bun run build:client`,
  $`bun run build:server`,
  $`bun run build:styles`,
]);

console.log("所有构建完成!");

使用 concurrently

bash
bun add -d concurrently
json
{
  "scripts": {
    "dev": "concurrently \"bun run dev:server\" \"bun run dev:client\"",
    "dev:server": "bun --watch src/server/index.ts",
    "dev:client": "bun --watch src/client/index.ts"
  }
}

脚本调试

VS Code 配置

创建 .vscode/launch.json

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "bun",
      "request": "launch",
      "name": "Debug Bun",
      "program": "${workspaceFolder}/src/index.ts",
      "cwd": "${workspaceFolder}",
      "stopOnEntry": false,
      "watchMode": false
    },
    {
      "type": "bun",
      "request": "launch",
      "name": "Debug Bun (Watch)",
      "program": "${workspaceFolder}/src/index.ts",
      "cwd": "${workspaceFolder}",
      "watchMode": true
    }
  ]
}

常见问题

脚本执行失败

bash
# 查看详细错误
bun run --verbose script-name

# 检查脚本语法
bun run --dry-run script-name

权限问题

bash
# Linux/macOS
chmod +x ./scripts/build.sh
bun run build

路径问题

json
{
  "scripts": {
    "start": "bun ./src/index.ts",
    "build": "bun build ./src/index.ts --outdir ./dist"
  }
}

使用 ./ 明确相对路径。

小结

本章介绍了:

  • ✅ 运行各种类型的脚本文件
  • ✅ 配置和运行 package.json 脚本
  • ✅ 使用监听和热重载模式
  • ✅ 调试和性能选项
  • ✅ 使用 Bun Shell 和 bunx
  • ✅ 多环境配置和生命周期钩子

下一步

继续阅读 包管理器 了解 Bun 的高速包管理功能。

本站内容仅供学习和研究使用。