ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Bun 开发实战指南:基于 agentic-awesome-skills 技能库全面掌握 Bun 运行时

Bun 开发实战指南:基于 agentic-awesome-skills 技能库全面掌握 Bun 运行时 AI 技能AI 插件【免费下载链接】agentic-awesome-skillsAAS Core is the local, agent-first control plane for complete catalog discovery, agent-owned selection, stack validation, and planning, backed by 2,400 agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.项目地址https://gitcode.com/gh_mirrors/an/agentic-awesome-skills点击查看免费下载导读本文是 AASagentic-awesome-skills技能库中bun-development技能的详细指南系统讲解如何在 Bun 运行时上完成现代 JavaScript/TypeScript 开发。你将掌握 Bun 的安装与项目初始化、包管理、代码运行与热更新、内置 API文件系统、HTTP/WebSocket 服务器、SQLite、密码哈希、内置测试运行器、生产级打包与单文件编译以及从 Node.js 平滑迁移的完整路径。全文代码均可在本仓库对应的技能文件 detailed-guide.md 与 SKILL.md 中溯源。在 AAS 技能库中bun-development是一条由社区贡献source: community的技能风险等级标记为critical于 2026-02-27 收录见 SKILL.md 头部元数据并在技能索引 data/skills_index.json 中被归类为web-development支持 Codex 与 Claude 两个插件目标端。它适用于以下场景使用 Bun 启动新 JS/TS 项目、从 Node.js 迁移到 Bun、优化开发速度、使用 Bun 内置工具打包器、测试运行器以及排查 Bun 特有问题的调试。1. 安装与选型为什么要用 Bun1.1 多平台安装方式原文档提供了四种主流安装路径覆盖 macOS / Linux / Windows 以及通过 npm 安装的备选方案# macOS / LinuxHomebrew 官方 tap brew install oven-sh/bun/bun # 备选方案下载官方安装脚本先审查再执行安全性最佳实践 tmpdir$(mktemp -d) trap rm -rf $tmpdir EXIT curl -fsSLo $tmpdir/bun-install.sh https://bun.sh/install cat $tmpdir/bun-install.sh # 执行前完整审阅安装脚本内容 bash $tmpdir/bun-install.sh # WindowsPowerShell powershell -NoProfile -Command Invoke-WebRequest https://bun.sh/install.ps1 -OutFile $env:TEMP\\bun-install.ps1; Get-Content $env:TEMP\\bun-install.ps1 -TotalCount 120; powershell -ExecutionPolicy Bypass -File $env:TEMP\\bun-install.ps1 # Homebrew 二段式安装先 tap 再 install brew tap oven-sh/bun brew install bun # npm 安装已有 Node 环境时使用 npm install -g bun升级直接执行bun upgrade即可将 Bun 升级到最新版本。值得强调的是文档给出的“下载脚本后先cat审阅再执行”的做法与本仓库 SECURITY_GUARDRAILS.md 强调的供应链安全意识一致——在执行任何来自网络的安装脚本前应确认其内容可信。1.2 Bun 与 Node.js 的核心差异原文档给出了 Bun 相对 Node.js 的对比表这也是选择 Bun 的核心依据特性BunNode.js启动时间~25ms~100ms依赖安装快 10-100 倍基线BaselineTypeScript原生支持需额外转译器JSX原生支持需额外转译器测试运行器内置外部Jest、Vitest打包器内置外部Webpack、esbuild说明上表数据来源于本技能文档 detailed-guide.md 的原始表述属于 Bun 官方宣传口径的引用实际性能表现会因机器、项目规模与负载而异建议以你自己的基准测试为准。2. 项目搭建从零初始化到工程化配置2.1 创建新项目# 交互式初始化项目 bun init # 生成的文件结构 # ├── package.json # ├── tsconfig.json # ├── index.ts # └── README.md # 使用特定模板创建项目 bun create template project-name # 常见模板示例 bun create react my-app # React 应用 bun create next my-app # Next.js 应用 bun create vite my-app # Vite 应用 bun create elysia my-api # Elysia API 服务bun init通过交互式问答生成最小可运行的 TypeScript 项目骨架bun create则从官方/社区模板脚手架完整应用适合业务项目初始化。2.2 package.json 的 Bun 最佳实践{ name: my-bun-project, version: 1.0.0, module: index.ts, type: module, scripts: { dev: bun run --watch index.ts, start: bun run index.ts, test: bun test, build: bun build ./index.ts --outdir ./dist, lint: bunx eslint . }, devDependencies: { types/bun: latest }, peerDependencies: { typescript: ^5.0.0 } }关键要点module: index.ts是 Bun 识别的入口字段对 ESM 项目友好dev脚本使用bun run --watch实现文件变更自动重启测试脚本直接使用内置的bun test无需再安装 Jest/Vitesttypes/bun提供Bun.*全局 API 的类型声明是 TS 开发必需。2.3 面向 Bun 优化的 tsconfig.json{ compilerOptions: { lib: [ESNext], module: esnext, target: esnext, moduleResolution: bundler, moduleDetection: force, allowImportingTsExtensions: true, noEmit: true, composite: true, strict: true, downlevelIteration: true, skipLibCheck: true, jsx: react-jsx, allowSyntheticDefaultImports: true, forceConsistentCasingInFileNames: true, allowJs: true, types: [bun-types] } }这套配置与原文档给出的“Bun-optimized”版本一致moduleResolution: bundler适配 Bun 的打包语义allowImportingTsExtensions允许直接导入.ts文件因为noEmit下 Bun 直接执行源码、无需输出编译产物jsx: react-jsx启用 JSX 原生支持。注意types字段随版本演进可写为bun-types或types/bun两者对应同一套全局类型。3. 包管理bun install / add / remove / update3.1 安装依赖bun install # 按 package.json 安装全部依赖可简写 bun i # 添加依赖 bun add express # 常规依赖 bun add -d typescript # 开发依赖 bun add -D types/node # 开发依赖-D 为 -d 的别名 bun add --optional pkg # 可选依赖 # 从指定 registry 安装 bun add lodash --registry https://registry.npmmirror.com # 安装指定版本 bun add react18.2.0 # 精确版本 bun add reactlatest # 最新稳定版 bun add reactnext # 预发布版本 # 从 Git 仓库安装 bun add github:user/repo bun add githttps://github.com/user/repo.git3.2 移除与更新bun remove lodash # 移除依赖 bun update # 更新全部依赖遵守版本范围约束 bun update lodash # 更新指定包 bun update --latest # 忽略版本范围直接更新到最新 bun outdated # 检查过期依赖3.3 bunxnpm/npx 的替代品bunx可直接执行包内的二进制命令无需先写入node_modulesbunx prettier --write . # 格式化 bunx tsc --init # 初始化 tsconfig bunx create-react-app my-app # 脚手架 bunx -p typescript4.9 tsc --version # 使用指定版本的包执行 bunx cowsay Hello from Bun! # 临时执行工具3.4 Lockfile 管理# bun.lockb 是二进制锁文件解析更快 # 需要调试时可生成文本锁文件 bun install --yarn # 生成 yarn.lock文本可读 # 信任既有锁文件按锁定的精确版本安装CI 常用 bun install --frozen-lockfile--frozen-lockfile在 CI/CD 中保证构建可重复是本仓库 docs/WORKFLOWS.md 中强调的可复现构建理念在 Bun 侧的具体映射。4. 运行代码直接执行、Watch 模式与环境变量4.1 基础执行# 直接运行 TypeScript无需构建步骤 bun run index.ts # 运行 JavaScript bun run index.js # 带参数运行 bun run server.ts --port 3000 # 运行 package.json 中定义的脚本 bun run dev bun run build # 脚本短格式自动查找 package.json scripts bun dev bun build4.2 Watch 与 Hot 模式# 文件变更后自动重启进程 bun --watch run index.ts # 热更新模式保持进程、模块级热替换适合开发服务器 bun --hot run server.ts4.3 环境变量.env文件会被自动加载无需引入dotenv// 通过 Bun.env 读取推荐 const apiKey Bun.env.API_KEY; const port Bun.env.PORT ?? 3000; // 或使用 Node.js 兼容的 process.env const dbUrl process.env.DATABASE_URL;# 指定特定 env 文件运行 bun --env-file.env.production run index.ts--env-file支持指定文件路径为多环境dev/staging/production部署提供了与 docs/examples 中环境隔离实践一致的方案。5. 内置 API 深度解析Bun 内置了五大高频 API全部开箱即用无需任何第三方依赖。5.1 文件系统Bun.file 与 Bun.write// 读取文件惰性读取仅在需要时加载 const file Bun.file(./data.json); const text await file.text(); // 文本内容 const json await file.json(); // 直接解析 JSON const buffer await file.arrayBuffer(); // ArrayBuffer // 文件元信息 console.log(file.size); // 字节数 console.log(file.type); // MIME 类型 // 写入文件 await Bun.write(./output.txt, Hello, Bun!); await Bun.write(./data.json, JSON.stringify({ foo: bar })); // 流式读取大文件 const reader file.stream(); for await (const chunk of reader) { console.log(chunk); }Bun.file采用惰性求值配合stream()可高效处理大文件避免整文件载入内存。5.2 HTTP 服务器Bun.serveconst server Bun.serve({ port: 3000, // 标准 Web Fetch API 风格的请求处理器 fetch(request) { const url new URL(request.url); if (url.pathname /) { return new Response(Hello World!); } if (url.pathname /api/users) { return Response.json([ { id: 1, name: Alice }, { id: 2, name: Bob }, ]); } return new Response(Not Found, { status: 404 }); }, // 统一错误处理 error(error) { return new Response(Error: ${error.message}, { status: 500 }); }, }); console.log(Server running at http://localhost:${server.port});Bun.serve基于 Web 标准 Request/Response 模型fetch处理器天然支持异步error回调统一兜底异常——这套结构在 7.2 节构建 API 中同样复用。5.3 WebSocket 服务器const server Bun.serve({ port: 3000, // 在 fetch 中通过 server.upgrade 升级连接 fetch(req, server) { if (server.upgrade(req)) { return; // 升级成功进入 WebSocket 生命周期 } return new Response(Upgrade failed, { status: 500 }); }, websocket: { open(ws) { console.log(Client connected); ws.send(Welcome!); }, message(ws, message) { console.log(Received: ${message}); ws.send(Echo: ${message}); }, close(ws) { console.log(Client disconnected); }, }, });Bun 将 HTTP 与 WebSocket 统一在同一个Bun.serve中server.upgrade(req)返回真值表示协议升级成功之后所有消息通过websocket对象的open/message/close钩子驱动天然支持广播等实时场景。5.4 SQLitebun:sqliteimport { Database } from bun:sqlite; const db new Database(mydb.sqlite); // 建表 db.run( CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE ) ); // 插入预编译语句 const insert db.prepare(INSERT INTO users (name, email) VALUES (?, ?)); insert.run(Alice, aliceexample.com); // 单条查询 const query db.prepare(SELECT * FROM users WHERE name ?); const user query.get(Alice); console.log(user); // { id: 1, name: Alice, email: aliceexample.com } // 全量查询 const allUsers db.query(SELECT * FROM users).all();bun:sqlite是 Bun 原生内置的同步 SQLite 驱动prepare()预编译 run/get/all三步式 API 既直观又高效适合本地缓存、轻量持久化等场景无需额外安装better-sqlite3等原生模块。5.5 密码哈希Bun.password// 生成随机密码crypto 为全局对象 const password crypto.randomUUID(); // 哈希默认算法 const hash await Bun.password.hash(password); // 验证 const isValid await Bun.password.verify(password, hash); console.log(isValid); // true // 指定算法与成本参数 const bcryptHash await Bun.password.hash(password, { algorithm: bcrypt, cost: 12, // bcrypt 计算成本因子默认 10范围约 4-31 });Bun.password内置多种哈希算法如 bcryptverify会自动识别哈希中的算法标识因此即便哈希参数变化也能正确校验——这是用户认证系统的关键安全特性。6. 测试内置测试运行器 bun:test6.1 基础测试用例// math.test.ts import { describe, it, expect, beforeAll, afterAll } from bun:test; describe(Math operations, () { it(adds two numbers, () { expect(1 1).toBe(2); }); it(subtracts two numbers, () { expect(5 - 3).toBe(2); }); });6.2 运行测试bun test # 运行全部测试 bun test math.test.ts # 运行指定文件 bun test --grep adds # 按名称模式过滤 bun test --watch # 监听模式 bun test --coverage # 覆盖率报告 bun test --timeout 5000 # 全局超时毫秒6.3 常用断言 Matchersimport { expect, test } from bun:test; test(matchers, () { // 相等性 expect(1).toBe(1); expect({ a: 1 }).toEqual({ a: 1 }); expect([1, 2]).toContain(1); // 比较 expect(10).toBeGreaterThan(5); expect(5).toBeLessThanOrEqual(5); // 真值性 expect(true).toBeTruthy(); expect(null).toBeNull(); expect(undefined).toBeUndefined(); // 字符串 expect(hello).toMatch(/ell/); expect(hello).toContain(ell); // 数组 expect([1, 2, 3]).toHaveLength(3); // 异常 expect(() { throw new Error(fail); }).toThrow(fail); // 异步 await expect(Promise.resolve(1)).resolves.toBe(1); await expect(Promise.reject(err)).rejects.toBe(err); });bun:test的 matcher 覆盖相等、比较、真值、字符串、数组、异常与异步 Promiseresolves/rejects等主流断言场景API 风格与 Jest 高度接近迁移成本低。6.4 Mock 与 Spyimport { mock, spyOn } from bun:test; // Mock 函数 const mockFn mock((x: number) x * 2); mockFn(5); expect(mockFn).toHaveBeenCalled(); expect(mockFn).toHaveBeenCalledWith(5); expect(mockFn.mock.results[0].value).toBe(10); // 对对象方法打桩 const obj { method: () original, }; const spy spyOn(obj, method).mockReturnValue(mocked); expect(obj.method()).toBe(mocked); expect(spy).toHaveBeenCalled();mock用于创建可断言调用行为是否被调用、调用参数、返回结果的函数spyOn用于替换对象方法并保留调用记录。二者共同支撑单元测试中的隔离策略。7. 打包与编译从源码到生产产物7.1 CLI 基础打包# 生产打包 bun build ./src/index.ts --outdir ./dist # 带完整选项 bun build ./src/index.ts \ --outdir ./dist \ --target browser \ --minify \ --sourcemap--target可选browser/bun/node决定打包产物面向的运行环境与外部依赖裁剪策略。7.2 Build API以编程方式打包const result await Bun.build({ entrypoints: [./src/index.ts], outdir: ./dist, target: browser, // 或 bun、node minify: true, sourcemap: external, splitting: true, // 代码分割 format: esm, // 输出模块格式 // 外部依赖不打入产物 external: [react, react-dom], // 定义全局常量 define: { process.env.NODE_ENV: JSON.stringify(production), }, // 输出命名规则 naming: { entry: [name].[hash].js, chunk: chunks/[name].[hash].js, asset: assets/[name].[hash][ext], }, }); if (!result.success) { console.error(result.logs); // 失败时输出诊断日志 }Bun.build是 CLI 的编程式等价物适合在构建脚本、CI 管线或工具链中动态调用result.success与result.logs提供结构化结果反馈。7.3 编译为单文件可执行程序# 生成独立可执行文件内含运行时无需预装 Bun bun build ./src/cli.ts --compile --outfile myapp # 交叉编译到其他平台 bun build ./src/cli.ts --compile --targetbun-linux-x64 --outfile myapp-linux bun build ./src/cli.ts --compile --targetbun-darwin-arm64 --outfile myapp-mac # 内嵌静态资源 bun build ./src/cli.ts --compile --outfile myapp --embed ./assets--compile把入口、依赖和 Bun 运行时一起打包成单一可执行文件--target支持跨平台交叉编译--embed将资源文件内嵌进二进制——这一能力与本仓库 scripts/activate-skills.sh 所倡导的“零外部依赖交付”理念一脉相承非常适合分发 CLI 工具。8. 从 Node.js 迁移到 Bun8.1 兼容性概览// 绝大多数 Node.js API 开箱即用 import fs from fs; import path from path; import crypto from crypto; // process 为全局对象 console.log(process.cwd()); console.log(process.env.HOME); // Buffer 为全局对象 const buf Buffer.from(hello); // __dirname 与 __filename 可用 console.log(__dirname); console.log(__filename);8.2 迁移四步走# 1. 安装 Bun brew install oven-sh/bun/bun # 2. 用 Bun 替换包管理器 rm -rf node_modules package-lock.json bun install # 3. 更新 package.json 脚本 # start: node index.js → start: bun run index.ts # test: jest → test: bun test # 4. 添加 Bun 类型 bun add -d types/bun8.3 与 Node.js 的差异对照// ❌ Node.js 专有写法在 Bun 中可能不可用 require(module) // 应改用 import require.resolve(pkg) // 应改用 import.meta.resolve __non_webpack_require__ // 不支持 // ✅ Bun 等价写法 import pkg from pkg; const resolved import.meta.resolve(pkg); Bun.resolveSync(pkg, process.cwd()); // ❌ 存在差异的全局 API process.hrtime() // 应使用 Bun.nanoseconds() setImmediate() // 应使用 queueMicrotask() // ✅ Bun 特色能力 const file Bun.file(./data.txt); // 快速文件 API Bun.serve({ port: 3000, fetch: ... }); // 快速 HTTP 服务器 Bun.password.hash(password); // 内置密码哈希迁移的关键纪律优先使用 ESMimport语义、import.meta.resolve做路径解析、Bun.nanoseconds()替代高精度计时将 Node 兼容写法替换为 Bun 原生 API 以获取最佳性能。9. 性能优化建议9.1 优先使用 Bun 原生 API// 较慢Node 兼容路径 import fs from fs/promises; const content await fs.readFile(./data.txt, utf-8); // 更快Bun 原生 const file Bun.file(./data.txt); const content await file.text();9.2 HTTP 服务优先 Bun.serve// 不推荐Express/Fastify存在额外开销 import express from express; const app express(); // 推荐Bun.serve原生实现性能显著更高 Bun.serve({ fetch(req) { return new Response(Hello!); }, }); // 或使用 Bun 深度优化的 Elysia 框架 import { Elysia } from elysia; new Elysia().get(/, () Hello!).listen(3000);原文档指出Bun.serve相比传统框架在吞吐上可达 4-10 倍优势若需要路由中间件等框架能力优先选择为 Bun 量身定做的 Elysia。9.3 生产环境务必打包压缩# 生产构建压缩 目标环境 bun build ./src/index.ts --outdir ./dist --minify --target node # 然后运行打包产物 bun run ./dist/index.js10. 速查表Quick Reference任务命令初始化项目bun init安装依赖bun install添加依赖bun add pkg运行脚本bun run script运行文件bun run file.ts监听模式bun --watch run file.ts运行测试bun test打包构建bun build ./src/index.ts --outdir ./dist执行包命令bunx pkg结语在 AAS 生态中使用本技能bun-development技能SKILL.md在本仓库中被标记为risk: critical意味着技能文档明确要求执行前必须完整阅读本文detailed-guide并将其中的安全约束、前置条件与验证要求视为强制项聚焦型任务按需加载对应章节端到端任务则需完整通读见 SKILL.md 的 Detailed Guide 章节。同时技能自身声明了使用边界仅在与上述场景明确匹配时使用不将输出视为环境特定验证、测试或专家评审的替代品当输入、权限、安全边界或成功标准缺失时应停止并请求澄清——这与 docs/QUALITY_BAR.md 中关于技能质量与责任边界的约定保持一致。对开发者而言本文覆盖的安装、项目搭建、包管理、运行、内置 API、测试、打包、迁移与性能优化九大主题构成了在 Bun 上从原型到生产的一条完整链路。你可以将本文档的代码示例直接落地验证并结合 data/skills_index.json 中该技能的索引信息分类web-development、Codex/Claude 双端支持、setup.type为none即开箱即用确认其在 AAS 目录中的可发现性与接入方式。赞分享AI 技能AI 插件【免费下载链接】agentic-awesome-skillsAAS Core is the local, agent-first control plane for complete catalog discovery, agent-owned selection, stack validation, and planning, backed by 2,400 agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.项目地址https://gitcode.com/gh_mirrors/an/agentic-awesome-skills点击查看免费下载相关推荐CubeSandbox调度增强路线图资源感知放置与实时再平衡CubeSandbox调度增强路线图资源感知放置与实时再平衡 CubeSandbox 是一个面向 AI Agent 的即时、并发、安全且轻量级的沙箱平台它的Agent 沙箱虚拟化云原生人工智能后端容器运行时Angular Expert 技能指南基于 Agentic Awesome Skills 掌握 Signals、Standalone 与 Zoneless 现代开发范式Angular Expert 技能指南基于 Agentic Awesome Skills 掌握 Signals、Standalone 与 Zoneless 现AI 技能AI 插件Azure Cosmos DB Java SDK 实战指南基于 agentic-awesome-skills 技能的全局分布式 NoSQL 开发Azure Cosmos DB Java SDK 实战指南基于 agentic awesome skills 技能的全局分布式 NoSQL 开发 本文以 agAI 技能AI 插件上一篇Functorch vs JAXPyTorch用户必须知道的5大差异下一篇ComfyUI-Lumi-Batcher工具启动延迟问题分析与解决方案创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表