TechLearn Hub

Learn Technology in Simple English

What Is Bun?

Bun is a fast JavaScript runtime and development toolkit designed for modern JavaScript and TypeScript applications.

Unlike tools that focus on only one part of development, Bun combines several important tools into one executable.

Simple idea: Bun is an all-in-one toolkit for running, installing, testing, building and developing JavaScript and TypeScript applications.

Why Was Bun Created?

Modern JavaScript projects often require several separate tools. For example, a developer may use Node.js as a runtime, npm as a package manager, Jest as a test runner and another tool for bundling.

Bun attempts to provide many of these capabilities through one integrated toolkit.

Important goals include:

Bun Is More Than a Runtime

A runtime allows JavaScript code to execute. Node.js is a well-known JavaScript runtime.

Bun also provides a runtime, but it goes further by including package management, testing and bundling capabilities.

Tool Purpose
Bun Runtime Runs JavaScript and TypeScript
bun install Installs dependencies
bun test Runs tests
bun build Builds and bundles applications
Bun.serve() Creates HTTP servers

What Is the Bun Runtime?

The Bun runtime executes JavaScript and TypeScript outside the browser.

For example, create a file named:

hello.ts

Add:

console.log("Hello from Bun!");

Then run:

bun run hello.ts

Bun can execute TypeScript directly without requiring a separate TypeScript execution tool for this basic workflow.

How to Install Bun

Bun provides installation instructions for major operating systems.

On supported Unix-like systems, the official installation command is:

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

After installation, check the version:

bun --version
Important: Installation commands can change over time. Always check the official Bun documentation before installing Bun on a new machine.

Create a New Bun Project

Bun can initialize a new project with:

bun init

The command creates files that help you start a JavaScript or TypeScript project.

You can then add your application code and dependencies.

Bun Package Manager

Bun includes its own package manager.

The main installation command is:

bun install

It reads your project's package information and installs dependencies.

Bun is designed to be compatible with the Node.js package ecosystem, including existing package.json projects.

Installing a Package

You can install a package with:

bun add express

This adds Express as a project dependency.

For a development dependency:

bun add --dev typescript

Removing a Package

To remove a package:

bun remove express

This updates your project dependencies.

Running Scripts with Bun

Suppose your package.json contains:

{
  "scripts": {
    "dev": "node server.js"
  }
}

You can run the script with:

bun run dev

Bun can work with scripts already used by many Node.js projects.

What Is bunx?

bunx is used to execute package binaries.

For example:

bunx create-vite

It is similar in purpose to tools such as npx.

Bun and TypeScript

TypeScript is an important part of modern web development.

Bun can run TypeScript files directly in many development workflows.

const name: string = "TechLearn Hub";

console.log(name);

Run it with:

bun run index.ts

Bun and JavaScript

Normal JavaScript works with Bun too.

const numbers = [1, 2, 3, 4, 5];

const total = numbers.reduce(
  (sum, number) => sum + number,
  0
);

console.log(total);

Run:

bun run index.js

Bun and JSX

Bun supports JSX as part of its JavaScript and frontend tooling.

function App() {
  return (
    <h1>Hello Bun</h1>
  );
}

export default App;

This makes Bun useful in React-based workflows.

Bun and React

Bun can be used with React projects.

A React project can use Bun for dependency installation, development scripts, testing and building.

Bun also provides commands for creating React projects through its project initialization workflow.

Bun Frontend Development

Bun can serve frontend applications during development.

For example, a project containing an HTML entry point can be served through Bun's development tooling.

bun ./index.html

Modern Bun versions support development features such as hot reloading for frontend workflows.

What Is Bun.build?

Bun provides a built-in bundler through Bun.build().

The bundler can process JavaScript, TypeScript, CSS, HTML and other supported files.

A basic example looks like this:

const result = await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist"
});

if (!result.success) {
  console.error(result.logs);
}

Bun Build from the Command Line

You can also use the command-line build tool.

bun build ./src/index.ts

For a production-style build:

bun build ./src/index.ts --production

The exact output can be controlled with build options.

Bundling a React Application

Bun's bundler supports JSX and TypeScript workflows.

bun build ./src/index.tsx --outdir ./dist

The resulting files can then be used as part of a deployment workflow.

Tree Shaking

Tree shaking removes code that is not needed by the final application when the build system can safely determine that it is unused.

This can help reduce the amount of JavaScript shipped to users.

Code Splitting

Code splitting divides an application into smaller pieces.

Instead of loading every piece of JavaScript immediately, parts of the application can be loaded when they are needed.

This is particularly useful for larger web applications.

Bun Test

Bun includes a built-in test runner.

The command is:

bun test

Bun's test runner supports TypeScript and JSX, mocks, snapshots, DOM testing and other testing features.

Writing a Simple Test

Create:

math.test.ts

Then:

import { test, expect } from "bun:test";

test("addition works", () => {
  expect(2 + 3).toBe(5);
});

Run:

bun test

Bun's official documentation describes bun:test as a Jest-compatible built-in test runner.

Bun HTTP Server

Bun provides an HTTP server API through Bun.serve().

const server = Bun.serve({
  port: 3000,

  fetch(request) {
    return new Response("Hello from Bun!");
  }
});

console.log(server.url);

This creates a simple HTTP server.

Bun Routes

Modern Bun server applications can define routes.

const server = Bun.serve({
  port: 3000,

  routes: {

    "/": new Response("Home"),

    "/about": new Response("About"),

    "/api": Response.json({
      message: "API is working"
    })

  }
});

console.log(server.url);

Routes can return normal responses or JSON responses.

Bun and WebSockets

Bun includes WebSocket server capabilities.

WebSockets allow applications to maintain a persistent connection between a client and server.

They are useful for:

Bun and Databases

Bun includes APIs and integrations for working with data stores.

Depending on the application, developers can work with technologies such as:

Always check current Bun documentation for the exact API and support available for your chosen database.

Bun and SQLite

SQLite is a lightweight relational database that is useful for many small applications.

Bun provides built-in database capabilities that can simplify database development.

A database can be useful for:

Bun and PostgreSQL

PostgreSQL is a powerful relational database commonly used in production applications.

Bun provides a built-in SQL client for PostgreSQL and other supported database workflows.

Bun and Redis

Redis is an in-memory data store commonly used for caching, sessions, queues and fast application data.

Bun includes Redis-related capabilities in its toolkit.

Bun and S3 Storage

Bun includes an S3 API for working with S3-compatible object storage.

Object storage can be used for:

Environment Variables

Applications often need configuration values such as API keys, database URLs and application secrets.

Environment variables are commonly used for this purpose.

const apiKey = process.env.API_KEY;

console.log(apiKey);
Never publish private API keys or passwords inside public source code.

Bun Shell

Bun provides a shell API through $.

import { $ } from "bun";

await $`echo Hello`;

This can be useful for development scripts and automation.

Single-File Executables

Bun can compile applications into standalone executables.

For example:

bun build ./cli.ts \
  --compile \
  --outfile todo

The compiled executable can include the application and Bun runtime.

Bun also provides options for cross-compilation and deployment workflows.

Bun and Node.js

Bun is designed with compatibility with the Node.js ecosystem in mind.

Many existing Node.js projects can be used with Bun with little or no modification, although compatibility is not identical for every API or package.

Feature Bun Node.js
JavaScript runtime Yes Yes
TypeScript execution Built in Usually requires tooling
Package manager Built in npm commonly used
Test runner Built in Built-in node:test
Bundler Built in External tools commonly used

Bun vs npm

npm is primarily a package manager and is widely used in the JavaScript ecosystem.

Bun includes a package manager as part of its larger toolkit.

Feature Bun npm
Package installation Yes Yes
JavaScript runtime Yes No
Built-in test runner Yes No equivalent as its core purpose
Bundler Yes Not its core purpose

Bun vs Deno

Feature Bun Deno
JavaScript runtime Yes Yes
TypeScript support Yes Yes
Package management Built in Built in
Bundler Built in Tooling included
Node compatibility Strong compatibility goal Compatibility layer available

These tools have different designs and should be selected according to the needs of the project.

Bun vs Vite

Bun and Vite overlap in some frontend development tasks but they are not identical tools.

Vite is primarily known as a frontend development tool and build system, while Bun is an all-in-one JavaScript runtime and toolkit.

Bun vs Webpack

Webpack is a highly configurable JavaScript bundler.

Bun provides bundling as one part of a much larger toolkit.

A developer choosing between them should consider the existing project, ecosystem, configuration requirements and framework support.

Bun Project Structure

my-app/
│
├── src/
│   ├── index.ts
│   └── server.ts
│
├── tests/
│   └── math.test.ts
│
├── package.json
├── bun.lock
└── tsconfig.json

The exact structure can change depending on the framework and project.

Example package.json

{
  "name": "my-bun-app",

  "scripts": {
    "dev": "bun run server.ts",
    "test": "bun test",
    "build": "bun build ./src/index.ts --outdir ./dist"
  }
}

You can run:

bun run dev

Tests:

bun test

Build:

bun run build

Building a Small Bun API

Here is a simple example of an HTTP API:

const server = Bun.serve({
  port: 3000,

  routes: {

    "/": new Response("Welcome"),

    "/api/users": Response.json([
      {
        id: 1,
        name: "Ali"
      },
      {
        id: 2,
        name: "Umar"
      }
    ])

  }
});

console.log(
  `Server running at ${server.url}`
);

This demonstrates how Bun can handle both the server and application logic.

Building a Simple Bun Test

import {
  test,
  expect
} from "bun:test";

function multiply(a, b) {
  return a * b;
}

test(
  "multiplication works",
  () => {

    expect(
      multiply(4, 5)
    ).toBe(20);

  }
);

Run:

bun test

Building a Frontend with Bun

A simple frontend project can contain:

index.html
src/
  app.tsx
  styles.css
package.json

Bun can participate in the development and build workflow for JavaScript, TypeScript, JSX, CSS and HTML.

Hot Reloading

Hot reloading means that changes to source files can be reflected quickly during development.

This creates a faster feedback loop because developers do not have to manually rebuild the entire application after every small change.

Production Builds

Before deploying an application, developers normally create a production build.

bun build ./index.html --production

Production builds can apply optimizations such as minification, tree shaking and code splitting when supported by the build workflow.

Advantages of Bun

Things to Consider

Do not switch an important production application from another runtime without testing the complete application and dependencies.

Common Beginner Mistakes

  1. Thinking Bun is only a package manager.
  2. Thinking Bun replaces JavaScript.
  3. Thinking Bun automatically makes every application faster.
  4. Ignoring package compatibility.
  5. Publishing API keys in source code.
  6. Skipping tests before deployment.
  7. Using outdated Bun commands from old tutorials.

Useful Bun Commands

Command Purpose
bun --version Show Bun version
bun init Create a project
bun install Install dependencies
bun add package Add a dependency
bun remove package Remove a dependency
bun run file.ts Run a file
bun run dev Run a package script
bunx package Run a package binary
bun test Run tests
bun build Build and bundle

Bun Learning Roadmap

  1. Learn JavaScript fundamentals.
  2. Learn TypeScript.
  3. Understand Node.js.
  4. Install Bun.
  5. Learn bun init.
  6. Learn bun install.
  7. Learn bun run.
  8. Learn Bun.serve().
  9. Learn bun:test.
  10. Learn bun build.
  11. Build a small API.
  12. Build a frontend.
  13. Connect a database.
  14. Test the application.
  15. Create a production build.
  16. Deploy the application.

Bun Cheat Sheet

Concept Meaning
Bun JavaScript runtime and toolkit
bun install Install dependencies
bun add Add a package
bun run Run files and scripts
bunx Run package binaries
bun test Run tests
bun build Bundle application code
Bun.serve() Create an HTTP server
Bun.build() Programmatic build API
bun:test Built-in testing module

Frequently Asked Questions

Is Bun a programming language?

No. Bun is a JavaScript runtime and development toolkit.

Is Bun a replacement for Node.js?

Bun can be used as a JavaScript runtime and aims for strong Node.js compatibility, but it is not identical to Node.js.

Can Bun run TypeScript?

Yes. Bun supports TypeScript execution as part of its runtime.

Can Bun install npm packages?

Yes. Bun's package manager is designed to work with the npm ecosystem.

Can Bun build websites?

Yes. Bun includes frontend development and bundling capabilities.

Can Bun run tests?

Yes. Bun includes the built-in bun:test test runner.

Can Bun create an API server?

Yes. Bun provides Bun.serve() for HTTP server applications.

Can Bun work with React?

Yes. Bun can be used with React projects and modern frontend workflows.

Does Bun support WebSockets?

Yes. Bun includes WebSocket server functionality.

Is Bun free?

Bun is open-source software and can be used as a development tool.

Conclusion

Bun is an important modern JavaScript technology because it combines several development tools into one toolkit.

Instead of separately managing a runtime, package manager, test runner and bundler, developers can use Bun for many of these tasks.

Bun is especially interesting for developers working with JavaScript, TypeScript, React, APIs, databases and modern web applications.

Remember: Bun is not simply another package manager. It is a complete JavaScript runtime and toolkit containing a runtime, package manager, test runner and bundler.