
Bun ports TypeScript-go into rust, 3x to 6.4x faster than tsc 7.0.2
powershell -c "irm bun.sh/install.ps1|iex"
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
BlogBun v1.4.3
Jarred Sumner
·October 10, 2026
To install Bun
curlnpmpowershellscoopbrewdocker
curl
curl -fsSL https://bun.sh/install | bash
npm
powershell -c "irm bun.sh/install.ps1|iex"
scoop
brew tap oven-sh/bun
brew install bun
docker
docker pull oven/bun
docker run --rm --init --ulimit memlock=-1:-1 oven/bun
To upgrade Bun
bun upgrade
bun check: a TypeScript type checker built into Bun#
bun check is an incredibly fast TypeScript type checker that passes 100% of TypeScript 7.0.2's conformance test suite.
bun check
1 | import { greet } from "./user"; 2 | 3 | const message = greet({ id: "1", name: "Ada" }); ^ error: TS2322: Type 'string' is not assignable to type 'number'. at src/index.ts:3:25
Found 1 error in 1 file, checked 2 files [14.00ms]
It's 3x to 6.4x faster than tsc 7.0.2, on a 16-core Apple silicon Mac:
It's a port of typescript-go. It reads your tsconfig.json, reports the same errors as tsc, and uses every CPU core. You don't need the typescript package installed.
It only type checks. It doesn't emit JavaScript or .d.ts files, and there's no language server, so your editor keeps using TypeScript.
Type check, then run. If there's a type error, your code doesn't run.
bun run --check src/index.ts
1 | import { greet } from "./user"; 2 | 3 | console.log(greet({ id: "1", name: "Ada" })); ^ error: TS2322: Type 'string' is not assignable to type 'number'. at src/index.ts:3:21
2 | id: number; ^ note: The expected type comes from property 'id' which is declared here on type 'User' at src/user.ts:2:3
Found 1 error in 1 file, checked 2 files [24.00ms]
It also works with package.json scripts (bun run --check dev) and with --watch, which checks again before every restart.
Type check the test files and everything they import, then run the tests. If there's a type error, no tests run.
bun test --check
bun test v1.4.3 4 | test("greet", () => { 5 | expect(greet({ id: "1", name: "Ada" })).toBe("hello Ada"); ^ error: TS2322: Type 'string' is not assignable to type 'number'. at src/user.test.ts:5:18
2 | id: number; ^ note: The expected type comes from property 'id' which is declared here on type 'User' at src/user.ts:2:3
Found 1 error in 1 file, checked 2 files [23.94ms]
bun build --check#
Type check, then bundle. A type error fails the build like any other build error, and nothing is written.
bun build --check ./src/index.ts --outdir out
3 | console.log(greet({ id: "1", name: "Ada" })); ^ error: TS2322: Type 'string' is not assignable to type 'number'. at /app/src/index.ts:3:21
2 | id: number; ^ note: TS6500: The expected type comes from property 'id' which is declared here on type 'User' at /app/src/user.ts:2:3
Bun.build takes check: true.
Every commit of Bun runs TypeScript 7.0.2's complete conformance test suite (and we will continue to keep it up-to-date as TypeScript itself updates).
For a project as complex as a TypeScript type checker, conformance tests aren't enough, so we deliberately misconfigured 72 popular open-source repositories and compared bun check's output with tsc's output.
Missing node_modules, mismatched TypeScript versions, no build step. Every error has to match: same file, line, column and error code.
The one mismatch is in vuejs/core. tsc only reports that error when global.ts comes before model.ts in files.
We ran 69 of them again under 11 other sets of compiler options:
Each fuzzer generates every combination of a set of language features, runs tsc and bun check on the result, and diffs the output.
Those run on every commit. These are larger runs we did offline:
162 of the 191 mismatches are in code that refers to itself while it's being declared, like class A { x = { a: null! as { p: A["x"] } } }.
For mutation testing, we broke Effect's source 913 times (swapped arguments, dropped type arguments, deleted overloads) and compared every error.
bunx -p typescript@7.0.2 tsc --noEmit --pretty false > tsc.txt bun check --no-pretty > bun.txt diff tsc.txt bun.txt
If there's a difference, that's a bug in Bun. Please open an issue.
Bun.FetchSession gives a group of requests their own TLS, proxy, and keep-alive settings and their own connection pool. Sessions never share connections with each other or with plain fetch().
const session = new Bun.FetchSession({ tls: { ca: await Bun.file("corp-ca.pem").text() }, proxy: { url: "http://proxy.internal:8080" }, keepAlive: { idleTimeout: 30, maxIdleSockets: 8 }, });
const client = new SomeClient({ fetch: session.fetch }); await fetch("https://example.com", { session }); // same thing
session.fetch is bound, so any client that accepts a fetch function can use it.
Options on the request override the session's.
session.close() (or using) closes idle connections.
A session's tls.checkServerIdentity runs once per connection. Requests that reuse the connection skip it.
Better proxy environment support in fetch()#
NO_PROXY accepts wildcards, CIDR blocks, bare IPv6 addresses, and host:port.
NO_PROXY="*.internal.example.com, 10.0.0.0/8, fd00::/8, localhost:3000"
ALL_PROXY is used when HTTP_PROXY / HTTPS_PROXY is unset. proxy: false ignores the proxy environment for one request.
await fetch("https://example.com", { proxy: false });
When a proxy refuses CONNECT with a non-2xx status, fetch() rejects with ERR_PROXY_TUNNEL. The error carries the proxy's status and headers. Before, fetch() resolved with the proxy's reply as if it came from the origin.
Run many instances of one app in a single process. Each graph gets fresh module state, its own require.cache, and its own timers and I/O. Parsed code and bytecode are shared between graphs.
const graph = new Bun.ModuleGraph({ globals: { process: tenantProcess }, onError: (error, kind) => console.error(kind, error), });
const app = await graph.import("./app.ts"); await graph.run(() => app.handle(request));
graph.dispose(); // closes the graph's servers, sockets, timers, child processes
graph.run(fn, ...args) calls fn in the graph's context, so what it opens belongs to the graph.
graph.dispose() (or using) behaves like worker.terminate(). It is not a security sandbox.
Bun.ModuleGraph.current is the graph whose context the caller is in.
--disallow-code-generation-from-strings blocks eval() and new Function()#
With Node's --disallow-code-generation-from-strings flag, eval() and new Function() throw. It covers the whole process, including every Worker. Bun used to accept the flag and ignore it.
new Function("return 1 + 1"); // EvalError: Code generation from strings disallowed for this context
=strict is Bun-only. It also blocks every other way a string becomes code: node:vm, import() of a data: URL, new Worker(code, { eval: true }), module._compile(), plugins that return source text, napi_run_script() and the inspector.
A flag embedded in a compiled executable always applies. BUN_OPTIONS can raise the level but not lower it.
bun build --compile ./server.ts --outfile server \
--compile-exec-argv="--disallow-code-generation-from-strings=strict"
Up to 2.7x faster large responses in node:http#
A response over 16 KB now goes out in one write per tick instead of up to 16. It applies to node:http and Bun.serve, over HTTP and HTTPS.
Requests per second from a node:http server:
node:http was slower than Node in six of eight large-response benchmarks. Now it's faster in all eight. A Bun.serve direct stream writing 4 × 16 KB is 83% faster. Small responses are unchanged.
Bun's JavaScriptCore engine picks up upstream WebKit performance work and spec fixes.
The JSON.parse numbers are against Bun v1.4.2 on an Apple silicon Mac, with manifests from 331 KB to 8 MB. The for...of and destructuring change helps code that hasn't reached the top JIT tier yet.
Promise.allSettled over thousands of throwing async calls no longer stalls. Attaching handlers to many promises that reject in the same turn took quadratic time. It is linear now.
await Promise.allSettled( Array.from({ length: 100_000 }, async () => { throw new Error("nope"); }), );
TimeAfter148 msBefore24 sNode.js475 ms
Attaching .catch() to 160,000 already-rejected promises went from 83 s to 24 ms.
Pass a level option to CompressionStream to trade ratio for speed. Brotli previously always ran at quality 11, which is very slow for large, dynamic responses.
const stream = new CompressionStream("brotli", { level: 4 });
gzip, deflate, deflate-raw: 0-9
brotli: 0-11
zstd: 1-22
Out-of-range values throw a RangeError. Omitting level keeps each format's current default.
Clients can safely resume a download from Bun.serve. A Range request with If-Range gets the range only if the file hasn't changed. Otherwise it gets the full body.
await fetch("http://localhost:3000/big.bin", { headers: { Range: "bytes=1000-", "If-Range": lastModified, // from the first response }, }); // 206 if the file is unchanged, 200 with the full body if it changed
It works for Bun.file responses and { dir } routes.
Without a lockfile, bun install and bun add no longer download tarballs for packages that never land in node_modules: bundled dependencies, packages for other platforms, and groups turned off by --production or --omit.
Tarballs downloaded with a cold cache and no lockfile:
Builds with many entry points or chunks use much less memory.
This fixes a regression from Bun v1.4.1 where bun build --splitting with ~800 chunks peaked at 7.7 GB instead of 6.2 GB. On Windows, it could abort with memory allocation of N bytes failed.
Large --splitting builds no longer fail with "Multiple files share the same output path". Before, two chunks with different contents could get the same 8-character [hash] name. Now both names get extra hash characters until they differ.
Use [hash9] through [hash13] to set a wider minimum hash. [hash13] is the full 64-bit hash.
await Bun.build({ entrypoints: ["./src/index.ts"], outdir: "./dist", splitting: true, naming: { chunk: "chunk-[hash13].[ext]" }, });
Metafile names the input file behind a split import()#
With --splitting, each dynamic import() in metafile.inputs has an entryPoint field naming the input file it loads, so tools that build a module graph no longer have to join through outputs. Metafile byte counts and --metafile-md output are now accurate too.
{ "path": "./chunk-abc123.js", "kind": "dynamic-import", "original": "./lazy.js", "entryPoint": "lazy.js", "external": true }
entryPoint is a key of inputs. A require() of an ES module with --target=bun gets one too. True externals like import("node:fs") don't.
New in bun build --compile#
bun build --compile supports profile-guided bytecode layout#
--bytecode-order lays out a --compile --bytecode executable from a profile of a real run. The bytecode that run used goes together at the front of the file.
In one large CLI app, cold start went from 1.01s to 0.53s. Resident bytecode memory at its prompt went from 59.5 MB to 20.5 MB.
bun build --compile --bytecode ./cli.ts --outfile myapp
Run it the way your users do. The profile is written on exit.
BUN_BYTECODE_ORDER_OUT=myapp.order ./myapp --help
bun build --compile --bytecode --bytecode-order=myapp.order ./cli.ts --outfile myapp
Functions are matched by a hash of their syntax, so a profile from an older build still applies.
--bytecode-order=a.order,b.order takes several profiles, most common first.
Bun.build uses compile: { bytecodeOrder: "./myapp.order" }.
bytecodeOrderStats() from bun:jsc reports how many loaded functions the profile covered.
Faster startup for --compile --bytecode executables#
Executables built with bun build --compile --bytecode start faster. ESM executables embed a pre-resolved module graph and optimized bytecode and load every bundled module in one pass, and JavaScriptCore does less work to decode embedded bytecode and link compiled fu
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。
