bun-init

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bun Project Initialization

Bun项目初始化

You are assisting with initializing a new Bun project. Follow these steps to create a well-structured project with optimal configurations.
您正在协助初始化一个新的Bun项目。请按照以下步骤创建结构清晰、配置优化的项目。

Workflow

工作流程

1. Check Prerequisites

1. 检查前置条件

First, verify Bun is installed:
bash
bun --version
If Bun is not installed, provide installation instructions for the user's platform.
首先,验证Bun是否已安装:
bash
bun --version
如果未安装Bun,请根据用户的操作系统提供安装说明。

2. Determine Project Type

2. 确定项目类型

Ask the user which type of project they want to create:
  • CLI Tool: Command-line application with bin entry point
  • Web App: Frontend application with React/Vue/etc
  • API Server: Backend API with routing framework
  • Library: Reusable package for publishing to npm
询问用户想要创建的项目类型:
  • CLI工具:带有bin入口的命令行应用
  • Web应用:使用React/Vue等框架的前端应用
  • API服务器:带有路由框架的后端API
  • :可发布至npm的可复用包

3. Run Bun Init

3. 运行Bun初始化命令

Execute the initialization command:
bash
bun init -y
This creates:
  • package.json
    with Bun-optimized scripts
  • tsconfig.json
    with recommended TypeScript settings
  • index.ts
    as the entry point
  • README.md
    with basic project info
执行初始化命令:
bash
bun init -y
该命令会创建以下文件:
  • 带有Bun优化脚本的
    package.json
  • 包含推荐TypeScript配置的
    tsconfig.json
  • 作为入口文件的
    index.ts
  • 包含基础项目信息的
    README.md

4. Enhance TypeScript Configuration

4. 优化TypeScript配置

Read the generated
tsconfig.json
and enhance it based on project type:
For CLI Tools:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
For Web Apps:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "types": ["bun-types"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
For API Servers:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
For Libraries:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "strict": true,
    "declaration": true,
    "declarationMap": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
读取生成的
tsconfig.json
,并根据项目类型进行优化:
针对CLI工具:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
针对Web应用:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "types": ["bun-types"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}
针对API服务器:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
针对库:
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "types": ["bun-types"],
    "strict": true,
    "declaration": true,
    "declarationMap": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowImportingTsExtensions": true,
    "noEmit": true
  }
}

5. Create Project Structure

5. 创建项目结构

Generate appropriate directory structure and files:
CLI Tool:
project/
├── src/
│   ├── index.ts          # Main CLI entry point
│   ├── commands/         # Command handlers
│   └── utils/            # Shared utilities
├── tests/
│   └── index.test.ts
├── package.json
├── tsconfig.json
├── .gitignore
├── .env.example
└── README.md
Create
src/index.ts
:
typescript
#!/usr/bin/env bun

console.log("Hello from Bun CLI!");

// Example: Parse command line arguments
const args = process.argv.slice(2);
console.log("Arguments:", args);
Update
package.json
to add bin field:
json
{
  "bin": {
    "your-cli-name": "./src/index.ts"
  }
}
Web App:
project/
├── src/
│   ├── index.tsx         # App entry point
│   ├── components/       # React components
│   ├── styles/           # CSS/styles
│   └── utils/            # Utilities
├── public/
│   └── index.html
├── tests/
├── package.json
├── tsconfig.json
├── .gitignore
├── .env.example
└── README.md
API Server:
project/
├── src/
│   ├── index.ts          # Server entry point
│   ├── routes/           # Route handlers
│   ├── middleware/       # Express/Hono middleware
│   ├── services/         # Business logic
│   └── types/            # TypeScript types
├── tests/
├── package.json
├── tsconfig.json
├── .gitignore
├── .env.example
└── README.md
Create
src/index.ts
:
typescript
const server = Bun.serve({
  port: 3000,
  fetch(request) {
    return new Response("Welcome to Bun!");
  },
});

console.log(`Server running at http://localhost:${server.port}`);
Library:
project/
├── src/
│   ├── index.ts          # Main export
│   └── types.ts          # Type definitions
├── tests/
├── package.json
├── tsconfig.json
├── .gitignore
└── README.md
生成合适的目录结构和文件:
CLI工具:
project/
├── src/
│   ├── index.ts          # 主CLI入口文件
│   ├── commands/         # 命令处理模块
│   └── utils/            # 共享工具函数
├── tests/
│   └── index.test.ts
├── package.json
├── tsconfig.json
├── .gitignore
├── .env.example
└── README.md
创建
src/index.ts
typescript
#!/usr/bin/env bun

console.log("Hello from Bun CLI!");

// 示例:解析命令行参数
const args = process.argv.slice(2);
console.log("Arguments:", args);
更新
package.json
添加bin字段:
json
{
  "bin": {
    "your-cli-name": "./src/index.ts"
  }
}
Web应用:
project/
├── src/
│   ├── index.tsx         # 应用入口文件
│   ├── components/       # React组件
│   ├── styles/           # CSS样式文件
│   └── utils/            # 工具函数
├── public/
│   └── index.html
├── tests/
├── package.json
├── tsconfig.json
├── .gitignore
├── .env.example
└── README.md
API服务器:
project/
├── src/
│   ├── index.ts          # 服务器入口文件
│   ├── routes/           # 路由处理模块
│   ├── middleware/       # Express/Hono中间件
│   ├── services/         # 业务逻辑层
│   └── types/            # TypeScript类型定义
├── tests/
├── package.json
├── tsconfig.json
├── .gitignore
├── .env.example
└── README.md
创建
src/index.ts
typescript
const server = Bun.serve({
  port: 3000,
  fetch(request) {
    return new Response("Welcome to Bun!");
  },
});

console.log(`Server running at http://localhost:${server.port}`);
库:
project/
├── src/
│   ├── index.ts          # 主导出文件
│   └── types.ts          # 类型定义文件
├── tests/
├── package.json
├── tsconfig.json
├── .gitignore
└── README.md

6. Create .gitignore

6. 创建.gitignore文件

Generate a comprehensive
.gitignore
:
gitignore
undefined
生成全面的
.gitignore
gitignore
undefined

Bun

Bun

node_modules bun.lockb *.bun
node_modules bun.lockb *.bun

Environment

Environment

.env .env.local .env.*.local
.env .env.local .env.*.local

Build outputs

Build outputs

dist/ build/ *.tsbuildinfo
dist/ build/ *.tsbuildinfo

Logs

Logs

logs .log npm-debug.log
logs .log npm-debug.log

OS

OS

.DS_Store Thumbs.db
.DS_Store Thumbs.db

IDE

IDE

.vscode/ .idea/ *.swp *.swo *~
.vscode/ .idea/ *.swp *.swo *~

Test coverage

Test coverage

coverage/ .nyc_output/
undefined
coverage/ .nyc_output/
undefined

7. Create Environment Template

7. 创建环境变量模板

Create
.env.example
:
bash
undefined
创建
.env.example
bash
undefined

Application

应用配置

NODE_ENV=development PORT=3000
NODE_ENV=development PORT=3000

Add your environment variables here

在此添加您的环境变量

DATABASE_URL=

DATABASE_URL=

API_KEY=

API_KEY=

undefined
undefined

8. Update package.json Scripts

8. 更新package.json脚本

Add project-type-specific scripts:
CLI Tool:
json
{
  "scripts": {
    "dev": "bun run src/index.ts",
    "test": "bun test",
    "lint": "bun run --bun eslint src",
    "typecheck": "bun run --bun tsc --noEmit"
  }
}
Web App:
json
{
  "scripts": {
    "dev": "bun run --hot src/index.tsx",
    "build": "bun build src/index.tsx --outdir=dist --minify",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit"
  }
}
API Server:
json
{
  "scripts": {
    "dev": "bun run --hot src/index.ts",
    "start": "bun run src/index.ts",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit"
  }
}
Library:
json
{
  "scripts": {
    "build": "bun build src/index.ts --outdir=dist --minify --sourcemap=external",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit",
    "prepublishOnly": "bun run build && bun test"
  }
}
添加与项目类型匹配的脚本:
CLI工具:
json
{
  "scripts": {
    "dev": "bun run src/index.ts",
    "test": "bun test",
    "lint": "bun run --bun eslint src",
    "typecheck": "bun run --bun tsc --noEmit"
  }
}
Web应用:
json
{
  "scripts": {
    "dev": "bun run --hot src/index.tsx",
    "build": "bun build src/index.tsx --outdir=dist --minify",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit"
  }
}
API服务器:
json
{
  "scripts": {
    "dev": "bun run --hot src/index.ts",
    "start": "bun run src/index.ts",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit"
  }
}
库:
json
{
  "scripts": {
    "build": "bun build src/index.ts --outdir=dist --minify --sourcemap=external",
    "test": "bun test",
    "typecheck": "bun run --bun tsc --noEmit",
    "prepublishOnly": "bun run build && bun test"
  }
}

9. Install Common Dependencies

9. 安装常用依赖

Suggest installing common dependencies based on project type:
CLI Tool:
bash
bun add commander chalk ora
bun add -d @types/node
Web App:
bash
bun add react react-dom
bun add -d @types/react @types/react-dom
API Server:
bash
bun add hono
bun add -d @types/node
Library:
bash
undefined
根据项目类型推荐安装常用依赖:
CLI工具:
bash
bun add commander chalk ora
bun add -d @types/node
Web应用:
bash
bun add react react-dom
bun add -d @types/react @types/react-dom
API服务器:
bash
bun add hono
bun add -d @types/node
库:
bash
undefined

No default dependencies - user will add as needed

无默认依赖 - 用户可按需添加

undefined
undefined

10. Create Initial Test File

10. 创建初始测试文件

Create a basic test file in
tests/
:
typescript
import { describe, expect, test } from "bun:test";

describe("Initial test", () => {
  test("basic assertion", () => {
    expect(1 + 1).toBe(2);
  });
});
tests/
目录下创建基础测试文件:
typescript
import { describe, expect, test } from "bun:test";

describe("Initial test", () => {
  test("basic assertion", () => {
    expect(1 + 1).toBe(2);
  });
});

Post-Initialization Checklist

初始化后检查清单

After completing the setup, provide the user with:
  1. ✅ Confirmation of project type created
  2. ✅ List of generated files and directories
  3. ✅ Next steps:
    • Copy
      .env.example
      to
      .env
      and configure
    • Run
      bun install
      if dependencies were suggested
    • Run
      bun dev
      to start development
    • Run
      bun test
      to verify tests work
完成设置后,向用户提供以下内容:
  1. ✅ 已创建的项目类型确认
  2. ✅ 生成的文件和目录列表
  3. ✅ 后续步骤:
    • 复制
      .env.example
      .env
      并配置环境变量
    • 如果推荐了依赖,运行
      bun install
      安装
    • 运行
      bun dev
      启动开发服务
    • 运行
      bun test
      验证测试是否正常工作

Key Configuration Principles

核心配置原则

  • Module Resolution: Use
    "moduleResolution": "bundler"
    for Bun's native resolution
  • TypeScript Types: Always include
    "types": ["bun-types"]
  • No Emit: Set
    "noEmit": true
    since Bun runs TypeScript directly
  • Import Extensions: Enable
    "allowImportingTsExtensions": true
    for
    .ts
    imports
  • Strict Mode: Enable strict TypeScript checks for better code quality
  • 模块解析:使用
    "moduleResolution": "bundler"
    以适配Bun的原生解析逻辑
  • TypeScript类型:始终包含
    "types": ["bun-types"]
  • 不生成编译产物:设置
    "noEmit": true
    ,因为Bun可直接运行TypeScript文件
  • 导入扩展名:启用
    "allowImportingTsExtensions": true
    以支持导入
    .ts
    文件
  • 严格模式:启用TypeScript严格检查以提升代码质量

Common Adjustments

常见调整

If user wants workspaces (monorepo):
Add to
package.json
:
json
{
  "workspaces": ["packages/*"]
}
If user wants path aliases:
Add to
tsconfig.json
:
json
{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"],
      "@components/*": ["./src/components/*"]
    }
  }
}
If user wants JSX without React:
Update
tsconfig.json
:
json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "preact" // or other JSX runtime
  }
}
如果用户需要工作区(单体仓库):
package.json
中添加:
json
{
  "workspaces": ["packages/*"]
}
如果用户需要路径别名:
tsconfig.json
中添加:
json
{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"],
      "@components/*": ["./src/components/*"]
    }
  }
}
如果用户需要不依赖React的JSX支持:
更新
tsconfig.json
json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "preact" // 或其他JSX运行时
  }
}

Completion

完成初始化

Once all files are created, inform the user that initialization is complete and provide a summary of:
  • Project structure
  • Available npm scripts
  • Recommended next steps
  • Links to Bun documentation for their project type
所有文件创建完成后,告知用户初始化已完成,并提供以下总结内容:
  • 项目结构说明
  • 可用的npm脚本列表
  • 推荐的后续操作
  • 对应项目类型的Bun文档链接