Bun foundations
Use watch mode and project scripts
Restart a Bun program when files change and give common project commands stable names in package.json.
During development we don’t want to restart the program by hand after every edit. Bun can watch the files our application loads and restart for us.
Run index.ts in watch mode:
bun --watch index.ts
Change the message in index.ts and save. Bun stops the old process and starts a new one, and the terminal shows the new output right away. It watches every file the program imports, not just the entry point, so an edit in a helper module triggers a restart too.
Bun also has a --hot flag. Instead of restarting the process it reloads the changed modules inside the running one. It’s useful for servers that hold state, but --watch is simpler and predictable, so that’s what we’ll use in this course.
Where the flag goes
Notice where --watch appears. Bun flags belong immediately after bun:
bun --watch run dev
If you put the flag at the end, like bun run dev --watch, Bun passes it to the script as an argument. Your program receives --watch in its arguments, nothing gets watched, and you sit there wondering why edits don’t show up. I’ve done this more than once.
Add project scripts
Scripts give the project a shared vocabulary. Instead of remembering flags, you and your teammates type the same short names.
Open package.json and add these entries:
{
"scripts": {
"dev": "bun --watch index.ts",
"start": "bun index.ts",
"typecheck": "tsc --noEmit"
}
}
Now start development with:
bun run dev
Run the program once, without watching, with:
bun run start
And check the TypeScript types with:
bun run typecheck
Notice that the typecheck script calls tsc directly. Inside a script, Bun adds the project’s node_modules/.bin to the PATH, so the locally installed TypeScript is found without bunx.
You can omit run for many scripts. I prefer bun run dev anyway. It makes the intention clear, and it avoids surprises when a script name matches one of Bun’s built-in commands, like test or install.
Forgot what scripts a project has? Run bun run with no script name. Bun lists every script from package.json along with the command it will execute. That’s the first thing I do when I open a project I haven’t touched in a while.
Lesson completed