Notes on bun features for better DX:
Basics
To create a blank project:
bun init
To start a project with the template:
bun create <template> [<destination>]
Run scripts from package.json
:
bun [bun flags] run <script> [script flags]
To run the CLI commands with bun
instead of node:
bun run --bun vite
Run from stdin:
echo "console.log('Hello')" | bun run -
To run with small memory usage:
bun --smol run index.ts
Prop punning
The Bun runtime also supports “prop punning” for JSX. This is a shorthand syntax useful for assigning a variable to a prop with the same name.
function Div(props: {className: string;}) {
const {className} = props;
// without punning
return <div className={className} />;
// with punning
return <div {className} />;
}
Env Vars
declare module "bun" {
interface Env {
AWESOME: string;
}
}
Production Build
Build an executable file with minification, byte-code, source-maps for error tracking and more:
bun build --compile --minify --sourcemap --bytecode ./path/to/my/app.ts --outfile myapp
Watch For Changes
Restart process on file changes:
bun --watch server.ts
Clear internal module cache which updates the code without restarting process (Vite For Servers):
bun --hot server.ts
Package Auto-Installation
If node_modules
exists, then use node module resolution.
else:
Installs the packages as they’re imported and saves to <BUN_GLOBAL_CACHE>/package/version
:
import { foo } from "foo"; // install `latest` version
Version Resolution For Bun-Style Module Resolution:
To determine which version to install, Bun follows the following algorithm:
- Check for a
bun.lockb
file in the project root. If it exists, use the version specified in the lockfile. - Otherwise, scan up the tree for a
package.json
that includes"foo"
as a dependency. If found, use the specified semver version or version range. - Otherwise, use
latest
.
Caveats: No npm intellisense. Uses
node_modules
for type resolution.
Local Package Patching
Change the package in node_modules
to fix bugs or make changes and call the following command to refresh the cache with the patched package:
bun patch react
Then commit all patches to ./patches
directory to retain in .git
across installs:
bun patch --commit react@17.0.2