umma.dev

Bun

What is Bun?

Bun is a toolkit which enables you do things in run time, can also be used as a package manager and a bundler.

Installation

npm install -g bun

Runtime (bun run)

Run JavaScript/TypeScript files and package.json scripts.

JavaScript/TypeScript

Run a file: bun run <file-name.js>

Supported file extensions: js, jsx, ts, tsx

Run file in watch mode: bun --watch run <file-name.js>*

  • Order matters, don’t put the --watch at the end of the command

package.json

bun [bun flags] run <script> [script flags]

"script": {
  "dev": "bun server.ts"
}

bun run dev

Package Manager

bun install

bun install is similar but faster than npm, yarn and pnpm.

bun install --production

bun install --dry-run

bun add

bun add <npm-package-name>

Dev dependencies: bun add --dev <package-name> or bun add -d <package-name>

Optional: bun add --optional <package-name>

Exact versions: bun add <package-name> --exact or bun add <package-name> -E

Global: bun add -g or bun install --global or bun add --global or bun install -g

To allow lifecyle scripts for a package: "trustedDependencies": ["package-name"]

bun remove

bun remove <package-name>

bun update

bun update

Use in a local directory to register the current package as a “linkable” package.

cd /path/to/your-package
cat package.jsom
bun link
cd /path/to/app
bun link your-package
{
  "dependencies": {
    "your-package": "link:your-package"
  }
}
cd /path/to/your-package
bun unlink

Bundler

Currently in Beta. Can be used via bun build CLI command.

cli: bun build ./index.tsx --outdir ./build

JavaScript:

await Bun.build({
  entrypoints: ["./index.tsx"],
  outdir: "./build",
});

Test Runner

bun test

bun test --test-name-pattern addition

bun test --timeout 20

bun test --rerun-each 100

bun test --bail or bun test --bail 10

bun test --watch

bun test --update-snapshots

SSR with Bun and ReactJS

Install Bun

curl -fsSL https://bun.sh/install | bash

Create Project

mkdir cd bun-project

bun init

## Bun Server

const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(`Bun!`);
  },
});

console.log(`Listening on http://localhost:${server.port} ...`);

Adding Packages

bun add react react-dom

bun add "types/react-dom -d

Run App

mv index.ts index.tsx

// index.tsx

import { renderToReadableStream } from "react-dom/server";
import Example from "./components/Example";

Bun.serve({
  async fetch(request) {
    const stream = await renderToReadableStream(<Example />);

    return new Response(stream, {
      headers: { "Content-Type": "text/html" },
    });
  },
});

console.log("Listening ...");

Run bun index.tsx and go to localhost:3000