Bun 不仅是一个专注性能与开发者体验的全新 JavaScript 运行时,还是一个快速的、全能的工具包,可用于运行、构建、测试和调试 JavaScript 和 TypeScript 代码,无论是单个文件还是完整的全栈应用。
Bun 优势
- 相比 Node.js ,Bun 可以直接运行 .js、.ts、.cjs、.mjs、.jsx、.tsx 文件。
- Bun 的速度非常快,启动速度比 Node.js 快 4 倍。当运行 TypeScript 文件时,这种差异会更加明显,因为在Node.js中运行TypeScript文件需要先进行转译才能运行。
安装 bun
# mac
brew install bun
# Windows
# 也以从 Bun 的 GitHub 发布页面下载 Windows 的预构建二进制文件,并手动添加到你的系统路径中。
scoop bucket add extras
scoop install bun
# npm 安装
npm install -g bun
# Linux
# 先添加 Bun 的 GPG 密钥
wget -qO- https://bun.sh/install | bash
# Docker
docker pull bunsh/bun
打包
Bun 的快速原生打包器。可通过 bun build CLI 命令或 Bun.build() JavaScript API 使用。
bun build ./src/index.tsx --outdir ./build --minify
Bun.build({
entrypoints: ["./src/index.tsx"],
outdir: "./build",
minify: true,
// ...
});
快速搭建一个 http 服务
npm install -g bun
mkdir bun
cd bun
npm init -y
bun add figlet
bun add -d @types/figlet bun-types
bun start
index.ts
import { serve, file } from "bun";
import figlet from "figlet";
const server = serve({
port: 3000,
fetch: async (request) =>{
// console.log(request.url)
let files = file('./package.json')
let json = await files.text()
const body = figlet.textSync("Hello , Bun !");
return new Response(`${body} \n\n ${json}`);
// console.log(json)
},
});
console.log(`Listening on http://localhost:${server.port} ...`);
在 package.json 中添加 start 启动命令,配置热更新,监听文件变化
{
"scripts": {
"start": "bun --hot index.ts"
}
}
bun 示例
HTTP server
const server = Bun.serve({
port: 3000,
fetch(request) {
return new Response("Welcome to Bun!");
},
});
console.log(`Listening on localhost:${server.port}`);
Websocket server
const server = Bun.serve<{ authToken: string; }>({
fetch(req, server) {
// use a library to parse cookies
const cookies = parseCookies(req.headers.get("Cookie"));
server.upgrade(req, {
data: { authToken: cookies['X-Token'] },
});
},
websocket: {
// handler called when a message is received
async message(ws, message) {
console.log(`Received: ${message}`);
const user = getUserFromToken(ws.data.authToken);
await db.Message.insert({
message: String(message),
userId: user.id,
});
},
},
});
console.log(`Listening on localhost:${server.port}`);
读写文件
const file = Bun.file(import.meta.dir + "/package.json"); // BunFile
const pkg = await file.json(); // BunFile extends Blob
pkg.name = "my-package";
pkg.version = "1.0.0";
await Bun.write(file, JSON.stringify(pkg, null, 2));
Hash 密码
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);
// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh...
const isMatch = await Bun.password.verify(password, hash);
// => true
浏览器打包
await Bun.build({
entrypoints: ["./index.tsx"],
outdir: "./build",
minify: true,
plugins: [
/* ... */
],
});
bun cli
| 类别 | 命令/标志 | 描述 |
|---|---|---|
| 命令 | run | 使用 Bun 执行文件。 |
| lint | 运行 package.json 脚本。 | |
| test | 使用 Bun 运行单元测试。 | |
| x | 执行包二进制文件(CLI),如有需要则安装之(bunx)。 | |
| repl | 启动一个和 Bun 交互的 REPL 会话。 | |
| install | 为 package.json 安装依赖项(bun i)。 | |
| add | 向 package.json 添加依赖项(bun a)。 | |
| remove | 从 package.json 移除依赖项(bun rm)。 | |
| update | 更新过时的依赖项。 | |
| link [] | 注册或链接本地 npm 包。 | |
| unlink | 注销本地 npm 包。 | |
| pm | 额外的包管理工具。 | |
| build | 将 TypeScript 和 JavaScript 打包成单个文件。 | |
| init | 从空白模板开始一个空的 Bun 项目。 | |
| create template | 从模板创建一个新项目(bun c)。 | |
| upgrade | 升级到 Bun 的最新版本。 | |
| --help | 打印命令的帮助文本。 | |
| 标志 | --watch | 文件变更时自动重启进程。 |
| --hot | 在 Bun 运行时、测试运行器或打包器中启用自动重载。 | |
| --smol | 使用更少的内存,但更频繁地运行垃圾收集。 | |
| -r, --preload | 在其他模块加载前导入一个模块。 | |
| --inspect | 激活 Bun 的调试器。 | |
| --inspect-wait | 激活 Bun 的调试器,在执行前等待连接。 | |
| --inspect-brk | 激活 Bun 的调试器,在代码的第一行设置断点并等待。 | |
| --if-present | 如果入口点不存在,则退出而不报错。 | |
| --no-install | 在 Bun 运行时禁用自动安装。 | |
| --install | 配置自动安装行为。选项包括 "auto"(默认,当没有 node_modules 时自动安装),"fallback"(仅当包缺失时),"force"(始终)。 | |
| -i | 执行时自动安装依赖项。等同于 --install=fallback。 | |
| -e, --eval | 将参数作为脚本进行评估。 | |
| --prefer-offline | 在 Bun 运行时跳过包的旧态检查,并从磁盘解析。 | |
| --prefer-latest | 在 Bun 运行时始终使用包的最新匹配版本,并总是检查 npm。 | |
| -p, --port | 设置 Bun.serve 的默认端口。 | |
| -b, --bun | 通过符号链接 node 强制脚本或包使用 Bun 的运行时而不是 Node.js。 | |
| --silent | 不打印脚本命令。 | |
| -v, --version | 打印版本并退出。 | |
| --revision | 打印版本和修订版并退出。 | |
| --env-file | 从指定文件加载环境变量。 | |
| --cwd | 绝对路径,用于解析文件和入口点。这会改变进程的当前工作目录。 | |
| -c, --config | 指定 Bun 配置文件的路径。默认为 $cwd/bunfig.toml。 | |
| -h, --help | 显示此菜单并退出。 |
bun API
| 主题 | APIs |
|---|---|
| HTTP 服务器 | Bun.serve |
| 打包器 | Bun.build |
| 文件 I/O | Bun.file Bun.write |
| 子进程 | Bun.spawn Bun.spawnSync |
| TCP 连接 | Bun.listen Bun.connect |
| 转译器 | Bun.Transpiler |
| 路由 | Bun.FileSystemRouter |
| 流式 HTML 变换 | HTMLRewriter |
| 哈希 | Bun.hash Bun.CryptoHasher |
| import.meta | import.meta |
| SQLite | bun:sqlite |
| 外部函数接口(FFI) | bun:ffi |
| 测试 | bun:test |
| Node-API | Node-API |
| 文件模式匹配(Glob) | Bun.Glob |
| 实用工具 | Bun.version Bun.revision Bun.env Bun.main Bun.sleep() Bun.sleepSync() Bun.which() Bun.peek() Bun.openInEditor() Bun.deepEquals() Bun.escapeHTML() Bun.fileURLToPath() Bun.pathToFileURL() Bun.gzipSync() Bun.gunzipSync() Bun.deflateSync() Bun.inflateSync() Bun.inspect() Bun.nanoseconds() Bun.readableStreamTo*() Bun.resolveSync() |
上表展示了 Bun 官方 API 页面中列出的主题和相关 API。Bun 实现了一组原生 API,这些 API 要么是直接挂载在全局的 Bun 对象上,要么是通过内置模块提供的。这些 API 经过了大量优化,是实现一些常见功能的官方“Bun 原生”方式。