Bun v0.7 大版本发布,与 Vite 牵手来破局?
大家好,很高兴又见面了,我是"高级前端?进阶?",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力。
今天给大家带来的主题是 Bun v0.7 发布,和大家一起细数该版本带来的核心特性。关于运行时以前也发表了不少文章,下面是部分文章的传送门:
- 《 JS Runtime vs. JS Engine!Deno/Bun/Node是运行时!》
- 《 前有Deno、后有Bun、Node.js已穷途末路?》
- 《 Node.js已死!Bun永生?》
- 《 Node.js、Deno、Bun 6大典型场景性能大PK?》
- 《 Deno v1.34 发布!全面拥抱 npm 生态 》
- 《 盘点全网最火的6+ JavaScript 运行时!Node/Deno/Bun 在列! 》
- 《 Bun v0.6.9 发布!》
- 《 运行时 Bun 又添王炸,支持 Bun宏!》
话不多说,直接进入正题!
前言
Bun 是一个速度极快的 JavaScript 运行时,集打包器、转译器和包管理器于一身。 在过去的几个月里,Bun 官方团队进行了很多更改,下面是每一个版本的发布特性:
- v0.6.10 : fs.watch()、bun install 错误修复、bun test 功能和改进的 CommonJS 支持
- v0.6.11 : 解决了 v0.6.10 的版本构建问题。
- v0.6.12 : Error.stack、Bun.file().exists() 和 Node.js 错误修复中的 Sourcemap 支持
- v0.6.13 :模拟日期、更快的 base64 编码以及针对 WebSocket 和 node:tls 的修复
- v0.6.14 : process.memoryUsage()、process.cpuUsage()、process.on('beforeExit', cb)、process.on('exit', cb) 和崩溃修复
可以通过下面的命令快速安装 Bun:
curl -fsSL https://bun.sh/install | bash
// 下面命令升级
bun upgrade
Vite 支持
Bun 运行时对 Vite 的支持仍处于实验阶段且并未优化。 Vite 不使用 Bun 的打包器、模块解析器或转译器,即使与 Bun 一起运行也是如此。
随着最近对 Node.js API 兼容性的进步,Bun 现在可以运行 vite dev,这是 Bun 获得最多支持的问题之一。要在 Vite 的入门项目之一中尝试此操作,请使用 Bunx。Bunx 是 Bun x 的别名,当开发者安装 bun 时,bunx CLI 将自动安装 Bunx。
bunx create-vite myapp
cd myapp
bun install
然后启动开发服务器:
bun --bun vite dev
--bun 标志告诉 Bun 覆盖 #!在 vite CLI 中 /usr/bin/env node shebang 并使用 Bun 而不是 Node.js 执行该文件,在未来的 Bun 版本中,这将是默认行为。
这是在构建前端应用程序时在服务器上使用 Bun 的 API 开发前端代码的好方法。
注意:如果在没有 -b 或 --bun 的情况下运行 Bun vite dev,它仍然会在 Node.js 中运行,因为 vite 的 CLI 在顶部指定 #!/usr/bin/env 节点,告诉 Bun(以及计算机上的其他软件)在 Node.js 中运行它。
与 Worker 的并发
Bun 现在支持 Worker,它允许开发者在单独的线程中运行另一个 JavaScript 实例。 在 Bun 中,workers 支持 ES 模块、CommonJS、TypeScript、JSX 以及 Bun 的其余功能,无需额外配置。
与在浏览器中一样,Worker 是一个全局类。 要从主线程创建工作线程:
bunx create-vite myapp
cd myapp
bun install
下面是 worker.ts 的内容:
addEventListener("message", (event: MessageEvent) => {
console.log("Message from main thread:", event.data);
postMessage("Hello from worker thread!");
});
此版本不包括对 node:worker_threads 模块的支持,但这解除了在 Bun 中实现它所需的工作。Bun 中添加了以下全局变量:
- postMessage
- addEventListener
- removeEventListener
- onmessage (getter/setter)
将 comlink 与 Bun 一起使用
流行的 comlink 包无需任何更改即可在 Bun 中运行。该库使得在主线程和工作线程之间共享函数和状态变得更加容易。
下面是 main.ts 的内容:
import * as Comlink from "comlink";
const worker = new Worker("./worker.ts");
// WebWorkers 使用“postMessage”,因此可以与 Comlink 一起使用。
const obj = Comlink.wrap(worker);
alert(`Counter: ${await obj.counter}`);
await obj.inc();
alert(`Counter: ${await obj.counter}`);
worker.ts 的内容如下:
import * as Comlink from "comlink";
const obj = {
counter: 0,
inc() {
this.counter++;
},
};
Comlink.expose(obj);
StructuredClone() 支持
与在浏览器中一样,postMessage 使用结构化克隆算法序列化消息。 Bun 现在通过 Web 标准的 StructuredClone() 函数实现了这一点,该函数提供了一种深度克隆对象的机制。 它与 JSON.parse(JSON.stringify(obj)) 类似,但支持更多类型。
const obj = { a: 1, b: 2 };
const clone = structuredClone(obj);
该方法还允许将原始值中的可转移对象转移而不是克隆到新对象,转移的对象与原始对象分离并附加到新对象,它们在原始对象中不再可访问。
// 16MB = 1024 * 1024 * 16
const uInt8Array = Uint8Array.from({ length: 1024 * 1024 * 16 }, (v, i) => i);
const transferred = structuredClone(uInt8Array, {
transfer: [uInt8Array.buffer],
});
console.log(uInt8Array.byteLength); // 0
异步本地存储支持
Bun 现在使用 node:async_hooks 模块实现 AsyncLocalStorage。 这提供了一种通过异步代码链传递上下文数据的机制,朝着支持 Next.js 和依赖此模块的其他框架迈出了一大步。
import { AsyncLocalStorage } from "node:async_hooks";
const requestId = new AsyncLocalStorage();
let lastId = 0;
Bun.serve({
fetch(request) {
lastId++;
// 设置“requestId”运行回调,async_hooks 将保留
// 这个值通过任何异步代码链。
return requestId.run(lastId, async () => {
console.log("Request ID: ${requestId getStore ()}");
await Bun.sleep(500);
// 即使新请求改变了'lastId','requestId'仍然被保留。
return new Response("Request ID: ${requestId. getStore ()}");
});
},
});
使用 bun --smol 减少内存使用
Bun --smol 是一个新的 CLI 标志,它将 JavaScriptCore 堆大小配置得更小且增长更慢,但会降低运行时性能。这对于在内存受限的环境中运行 Bun 很有用。
为了避免手动设置该标志,开发者可以在 Bunfig.toml 中将其设置为默认值。
smol = true
[test]
# set it only for tests, if you want
smol = true
bun test 支持--bail
使用 --bail=1 运行 Bun test 将在第一次测试失败后退出。
bun test --bail 1
bun test v0.7.0
? test1 [0.02ms]
test2.test.js:
1 | import {test, expect} from 'bun:test';
2 |
3 | test('test2', () => {
4 | expect(2).toEqual(3);
^
error: expect(received).toEqual(expected)
Expected: 3
Received: 2
at /Users/colinmcd94/Documents/bun/fun/test/test2.test.js:13:8
? test2 [0.18ms]
Ran 2 tests across 2 files. [8.00ms]
Bailed out after 1 failures
这对于 CI 环境或当想要在第一次失败后停止运行测试时非常有用。
Bun.readableStreamToFormData()
Bun 现在公开了一个帮助器,用于将 ReadableStream 转换为 FormData,它支持多部分表单数据。
import { readableStreamToFormData } from "bun";
// without dashes
const boundary = "WebKitFormBoundary" + Math.random().toString(16).slice(2);
const myStream = getStreamFromSomewhere(); // ...
const formData = await Bun.readableStreamToFormData(stream, boundary);
formData.get("foo"); // "bar"
它还支持 URL 编码的表单数据:
import { readableStreamToFormData } from "bun";
const stream = new Response("hello=123").body;
const formData = await readableStreamToFormData(stream);
formData.get("hello"); // "123"
添加此内容是为了帮助修复当正文是来自 JavaScript 的 ReadableStream 时导致 request.formData() 和 response.formData() 挂起的错误。
在 bun:jsc 中序列化和反序列化
Bun:jsc 模块现在导出 serialize() 和 deserialize(),运行开发者将 JavaScript 对象转换为 ArrayBuffer 并返回。
import { serialize, deserialize } from "bun:jsc";
import { deepEquals } from "bun";
const obj = { a: 1, b: 2 };
const buffer = serialize(obj);
const clone = deserialize(buffer);
if (deepEquals(obj, clone)) {
console.log("They are equal!");
}
node:v8 模块导出这些相同的函数,以便与在进程之间序列化/反序列化数据的现有库兼容。
WebSocket 改进
开发者现在可以手动发送和接收 WebSocket ping 和 pong 帧。
const ws = new WebSocket("wss://echo.websocket.org");
ws.addEventListener("pong", () => {
console.log("Received pong");
});
ws.ping();
这适用于 ServerWebSocket 和 WebSocket。
Ping 和 Pong 是websocket 里的心跳,用来保证客户端是在线,一般来说只有服务端给客户端发送Ping,然后客户端发送Pong来回应,表明自己仍然在线。
nodebuffer 现在是默认的 binaryType
默认情况下,Bun 中的 WebSocket 和 ServerWebSocket 的 binaryType 现在是 nodebuffer, 这意味着 WebSocket 中的二进制数据帧将是 Buffer 实例,而不是 ArrayBuffer(如之前),这是为了匹配 ws 包的行为。
const ws = new WebSocket("wss://echo.websocket.org");
ws.addEventListener("message", (event: MessageEvent) => {
console.log(event.data instanceof Buffer); // true
});
要将其更改回 ArrayBuffer,请设置 ws.binaryType = "arraybuffer"。
const ws = new WebSocket("wss://echo.websocket.org");
ws.binaryType = "arraybuffer";
// 请注意,在浏览器中默认为 Blob
ws.addEventListener("message", (event: MessageEvent) => {
event.data; // ArrayBuffer
});
Node.js 兼容性改进
此版本对 Node.js 兼容性添加了一些额外的改进。
Node:tls 对 TLSSocket 的改进
以下方法是在 TLSSocket 类上实现的,比如:
- .getPeerFinished()
- .getFinished()
- .getProtocol()
- .getSharedSigalgs()
- .isSessionReused()
- .exportKeyingMaterial()
- .setMaxSendFragment()
- .getPeerCertificate()
- .getCertificate()
- .enableTrace()
- .disableRenegotiation()
- .getCipher()
- .getEphemeralKeyInfo()
- .getTLSTicket()
- .getSession()
- .setSession()
base64url 哈希值不再是数据:url
以前,Bun 会将 data:base64 添加到 crypto.createHash("sha256").digest("base64url") 的输出中。这不是 Node.js 所做的,它会导致那些期望输出与 Node.js 的字符串相同的库出现问题。
crypto.createHash("sha256").update("abc").digest("base64url");
// Node.js输出: "ungWv48Bz-pBQUDeXa4iI7ADYaOWF3qctBD_YfIAFa0"
// Bun v0.7.0输出: "ungWv48Bz-pBQUDeXa4iI7ADYaOWF3qctBD_YfIAFa0"
// <= Bun v0.6.14输出: "data:base64,ungWv48Bz-pBQUDeXa4iI7ADYaOWF3qctBD_YfIAFa0="
带有 process.stdout.columns 和 process.stdout.rows 的终端维度
process.stdout 和 process.stderr 现在支持读取终端窗口的尺寸。
const { columns, rows } = process.stdout;
const [columns, rows] = process.stdout.getWindowSize();
const { columns, rows } = process.stderr;
const [columns, rows] = process.stderr.getWindowSize();
如果想要同时使用两个维度,则可以使用
process.stdout.getWindowSize()。
bug fix 修复
修复了 await new Response(latin1String).arrayBuffer() 和 await Response.json(obj).json() 中的内存泄漏。
修复后的数据如下:
cpu: Apple M1 Max
runtime: bun 0.7.0 (arm64-darwin)
benchmark time (avg) (min … max) p75 p99 p995
--------------------------------------------------------------------------------------------------- -----------------------------
new Response().arrayBuffer() (new string each call, latin1) 12.9 μs/iter (625 ns … 4.18 ms) 1 μs 567.17 μs 711.79 μs
new Response().arrayBuffer() (new string each call, utf16) 12.85 μs/iter (1.67 μs … 1.56 ms) 2.17 μs 462.75 μs 621.13 μs
new Response().arrayBuffer() (existing string, latin1) 6.53 μs/iter (6.21 μs … 7.07 μs) 6.64 μs 7.07 μs 7.07 μs
Peak memory usage: 49 MB
修复之前的数据为:
cpu: Apple M1 Max
runtime: bun 0.7.0 (arm64-darwin)
benchmark time (avg) (min … max) p75 p99 p995
--------------------------------------------------------------------------------------------------- -----------------------------
new Response().arrayBuffer() (new string each call, latin1) 13.51 μs/iter (541 ns … 3.2 ms) 1.92 μs 553.42 μs 709.92 μs
new Response().arrayBuffer() (new string each call, utf16) 13.07 μs/iter (1.71 μs … 3.43 ms) 2.13 μs 451.21 μs 651.67 μs
new Response().arrayBuffer() (existing string, latin1) 6.25 μs/iter (5.79 μs … 6.81 μs) 6.4 μs 6.81 μs 6.81 μs
Peak memory usage: 292 MB
导致 graphql 包导入相同模块的 CommonJS 和 ESM 版本的模块解析错误已得到修复。通过将 package.json 主字段顺序调整为更接近 Node.js 的顺序,可以解决此问题。
error: Cannot use GraphQLScalarType "String" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
本文总结
本文主要和大家探讨 Bun v0.7 发布,和大家一起细数该版本带来的核心特性。相信通过本文的阅读,大家对 Bun v0.7 会有一个初步的了解,同时也会有自己的看法。
因为篇幅有限,文章并没有过多展开,如果有兴趣,可以在我的主页继续阅读,同时文末的参考资料提供了大量优秀文档以供学习。最后,欢迎大家点赞、评论、转发、收藏!
参考资料
https://bun.sh/blog/bun-v0.7.0#improvements-to-tlssocket-from-node-tls
https://bun.sh/docs/cli/bunx
https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
https://developer.mozilla.org/en-US/docs/Web/API/FormData