温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/docs/runtime/watch-mode
点击访问原文链接

Watch Mode - Bun

Watch Mode - BunDocumentation Index

Fetch the complete documentation index at: /docs/llms.txt

Use this file to discover all available pages before exploring further.

Skip to main contentBun home pageSearch...⌘KInstall BunSearch...NavigationCore RuntimeWatch ModeRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicenseOn this page--watch mode--hot modeHTTP serversCore RuntimeWatch ModeCopy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">*]:[overflow-wrap:anywhere]">

Automatic reloading in Bun with —watch and —hot modes

Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">Bun supports two kinds of automatic reloading via CLI flags: --watch mode, which hard restarts Bun’s process when imported files change. --hot mode, which soft reloads the code (without restarting the process) when imported files change. ​--watch mode Watch mode can be used with bun test or when running TypeScript, JSX, and JavaScript files. To run a file in --watch mode: terminal
bun --watch index.tsx
To run your tests in --watch mode: terminal
bun --watch test
In --watch mode, Bun keeps track of all imported files and watches them for changes. When a change is detected, Bun restarts the process, preserving the same set of CLI arguments and environment variables used in the initial run. If Bun crashes, --watch will attempt to automatically restart the process. ⚡️ Reloads are fast. The filesystem watchers you’re probably used to have several layers of libraries wrapping the native APIs or worse, rely on polling.Instead, Bun uses operating system native filesystem watcher APIs like kqueue or inotify to detect changes to files. Bun also applies several optimizations to scale to larger projects (such as setting a high rlimit for file descriptors, statically allocated file path buffers, reuse file descriptors when possible, etc). The following examples show Bun live-reloading a file as it is edited, with VSCode configured to save the file on each keystroke. terminal
bun run --watch watchy.tsx
watchy.tsx
import { serve } from "bun";

console.log("I restarted at:", Date.now());

serve({
port: 4003,
fetch(request) {
return new Response("Sup");
},
});
In this example, Bun is Running bun test in watch mode and save-on-keypress enabled: terminal
bun --watch test
The --no-clear-screen flag is useful in scenarios where you don’t want the terminal to clear, such as when running multiple bun build --watch commands simultaneously using tools like concurrently. Without this flag, the output of one instance could clear the output of others, potentially hiding errors from one instance beneath the output of another. The --no-clear-screen flag, similar to TypeScript’s --preserveWatchOutput, prevents this issue. It can be used in combination with --watch, for example: bun build --watch --no-clear-screen. ​--hot mode Use bun --hot to enable hot reloading when executing code with Bun. This is distinct from --watch mode in that Bun does not hard-restart the entire process. Instead, it detects code changes and updates its internal module cache with the new code. This is not the same as hot reloading in the browser! Many frameworks provide a “hot reloading” experience, where you can edit & save your frontend code (say, a React component) and see the changes reflected in the browser without refreshing the page. Bun’s --hot is the server-side equivalent of this experience. To get hot reloading in the browser, use a framework like Vite. terminal
bun --hot server.ts
Starting from the entrypoint (server.ts in the example above), Bun builds a registry of all imported source files (excluding those in node_modules) and watches them for changes. When a change is detected, Bun performs a “soft reload”. All files are re-evaluated, but all global state (notably, the globalThis object) is persisted. server.ts
// make TypeScript happy
declare global {
var count: number;
}

globalThis.count ??= 0;
console.log(`Reloaded ${globalThis.count} times`);
globalThis.count++;

// prevent `bun run` from exiting
setInterval(function () {}, 1000000);
If you run this file with bun --hot server.ts, you’ll see the reload count increment every time you save the file. terminal
bun --hot index.ts
Reloaded 1 times
Reloaded 2 times
Reloaded 3 times
Traditional file watchers like nodemon restart the entire process, so HTTP servers and other stateful objects are lost. By contrast, bun --hot is able to reflect the updated code without restarting the process. ​HTTP servers This makes it possible, for instance, to update your HTTP request handler without shutting down the server itself. When you save the file, your HTTP server will be reloaded with the updated code without the process being restarted. This results in seriously fast refresh speeds. server.ts
globalThis.count ??= 0;
globalThis.count++;

Bun.serve({
fetch(req: Request) {
return new Response(`Reloaded ${globalThis.count} times`);
},
port: 3000,
});
Note — In a future version of Bun, support for Vite’s import.meta.hot is planned to enable better lifecycle management for hot reloading and to align with the ecosystem.

Implementation details

On hot reload, Bun: Resets the internal require cache and ES module registry (Loader.registry) Runs the garbage collector synchronously (to minimize memory leaks, at the cost of runtime performance) Re-transpiles all of your code from scratch (including sourcemaps) Re-evaluates the code with JavaScriptCore This implementation isn’t particularly optimized. It re-transpiles files that haven’t changed. It makes no attempt at incremental compilation. It’s a starting point.

Was this page helpful?

YesNoSuggest editsRaise issueBun RuntimePreviousDebuggingNext⌘IxgithubdiscordyoutubePowered byThis documentation is built and hosted on Mintlify, a developer documentation platform

Watch Mode - Bun,AI智能索引,全网链接索引,智能导航,网页索引

    Automatic reloading in Bun with --watch and --hot modes