Bun 脚本运行 #

基本用法 #

运行 package.json 脚本 #

json
{
  "scripts": {
    "start": "bun run src/index.ts",
    "dev": "bun --hot run src/index.ts",
    "build": "bun build src/index.ts --outdir dist",
    "test": "bun test"
  }
}
bash
# 运行脚本
bun run start
bun run dev

# 简写
bun start
bun dev

运行文件 #

bash
# 运行 TypeScript 文件
bun run src/index.ts

# 简写
bun src/index.ts

传递参数 #

bash
# 传递参数给脚本
bun start --port 3000 --host

# 在脚本中获取
const args = process.argv.slice(2);
console.log(args);  // ['--port', '3000', '--host']

生命周期脚本 #

常用生命周期 #

json
{
  "scripts": {
    "preinstall": "echo 'Before install'",
    "postinstall": "echo 'After install'",
    "prestart": "echo 'Before start'",
    "start": "bun run src/index.ts",
    "poststart": "echo 'After start'",
    "prebuild": "echo 'Before build'",
    "build": "bun build src/index.ts --outdir dist",
    "postbuild": "echo 'After build'",
    "pretest": "echo 'Before test'",
    "test": "bun test",
    "posttest": "echo 'After test'"
  }
}

执行顺序 #

bash
bun start
# 执行顺序: prestart -> start -> poststart

常用脚本配置 #

开发脚本 #

json
{
  "scripts": {
    "dev": "bun --hot run src/index.ts",
    "dev:debug": "bun --inspect run src/index.ts",
    "start": "bun run src/index.ts",
    "start:prod": "NODE_ENV=production bun run src/index.ts"
  }
}

构建脚本 #

json
{
  "scripts": {
    "build": "bun build src/index.ts --outdir dist --minify",
    "build:dev": "bun build src/index.ts --outdir dist",
    "build:analyze": "bun build src/index.ts --outdir dist --analyze",
    "clean": "rm -rf dist"
  }
}

测试脚本 #

json
{
  "scripts": {
    "test": "bun test",
    "test:watch": "bun test --watch",
    "test:coverage": "bun test --coverage",
    "test:ui": "bun test --ui"
  }
}

代码质量脚本 #

json
{
  "scripts": {
    "lint": "eslint src",
    "lint:fix": "eslint src --fix",
    "format": "prettier --write src",
    "format:check": "prettier --check src",
    "typecheck": "tsc --noEmit"
  }
}

跨平台脚本 #

使用 bun 跨平台 #

json
{
  "scripts": {
    "clean": "bun run scripts/clean.ts",
    "build": "bun run scripts/build.ts"
  }
}
typescript
// scripts/clean.ts
import { $ } from "bun";

await $`rm -rf dist`;
await $`rm -rf node_modules/.cache`;
console.log("Cleaned!");

下一步 #

现在你已经了解了 Bun 脚本运行,接下来学习 打包器 了解 Bun 的打包功能。

最后更新:2026-03-29