用 Bun 运行 TypeScript 项目:无需额外配置的开发体验

Bun 是一个现代化的 JavaScript 运行时,内置了原生 TypeScript 支持。这意味着你可以直接运行 .ts 文件而无需任何额外配置,彻底摆脱传统工具链的繁琐设置。以下是完整指南:


1. 安装 Bun

在终端执行以下命令(支持 macOS/Linux/WSL):

curl -fsSL https://bun.sh/install | bash

安装后验证版本:

bun --version


2. 创建 TypeScript 项目

直接编写 .ts 文件,例如 main.ts

// 无需 tsconfig.json 或编译器配置
const greet = (name: string): void => {
  console.log(`Hello ${name}!`);
};

greet("Bun User");  // 类型安全


3. 直接运行 TypeScript

执行命令即可运行(无需编译步骤):

bun run main.ts

输出结果:

Hello Bun User!


4. 核心优势
  • 零配置:自动处理类型检查和转译
  • 极速启动:比 Node.js + ts-node 快 4-5 倍
  • 完整工具链:内置测试、打包和包管理
    bun test             # 运行测试
    bun build ./main.ts  # 打包为单文件
    bun add zod          # 安装依赖(替代 npm/pnpm)
    


5. 对比传统工作流
步骤 Node.js + ts-node Bun
安装依赖 typescript, ts-node 仅 Bun
运行命令 ts-node main.ts bun main.ts
配置文件 tsconfig.json 无需任何配置
冷启动时间 500ms~1s <100ms

6. 高级用法
  • 热更新:开发时自动重载
    bun --hot main.ts
    

  • 导入 npm 包:直接使用 TypeScript 类型
    import { z } from "zod"; // 自动解析类型
    


7. 注意事项
  • Bun 目前(v1.0)对某些复杂类型体操的支持仍在完善中
  • 兼容性:覆盖 90% 的 Node.js API 和 Web API
  • 调试:使用 bun --inspect 连接 Chrome DevTools

通过 Bun,TypeScript 开发回归本质:专注代码而非配置。立即体验:

bun create vite my-ts-app # 创建 React/Vue TS 项目

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐