Bun | The all-in-one JavaScript runtime
Tags: javascript, webdev, beginners, tutorial
Published: 2023-09-23 17:50:44

In the ever-evolving realm of JavaScript development, a new entrant has made its debut — Bun 1.0. It’s not just any run-of-the-mill tool; it serves as a multifaceted JavaScript runtime and toolkit. The primary objective here is to simplify the development journey by removing unnecessary complexities. Bun is capable to a range of tasks, such as building, executing, testing, and debugging JavaScript and TypeScript. In essence, it offers a holistic solution for developers seeking efficiency.

What sets Bun apart is its distinct role as a drop-in replacement for Node.js. Furthermore, it proudly boasts compatibility with TypeScript and TSX files, and notably, it delivers superior speed compared to Node.js. A pivotal feature of Bun is its adeptness in supporting both Common JS and ES modules.

Another remarkable feature of Bun is its capacity for hot reloading, allowing code to be refreshed without the need for process restarts. This feature proves exceptionally handy during the development phase, where iterative changes are the norm. Additionally, Bun offers a plugin API for crafting custom loaders and extends its versatility by supporting YAML imports. These traits collectively make Bun a valuable asset in the toolkit of modern developers.

In this article, we will dive deeper into the world of Bun 1.0, exploring its features, benefits, and how it can revolutionize your JavaScript development journey. Buckle up, because the future of JavaScript development just got a whole lot more exciting with Bun.

## Getting Started
### Table of contents
- What is Bun
- Design goals
- Benchmarking
- Node vs Deno vs Bun
- Installation
- Experimenting with Bun
- Creating a simple HTTP server
- Creating a react application
- Bun for Next, Svelte, and Vue
- Bun Roadmap
- Useful Links

### What is Bun
Bun is a comprehensive toolkit tailored for JavaScript and TypeScript applications, centered around its high-performance Bun runtime. This runtime, written in Zig and harnessing the capabilities of JavaScriptCore, serves as a seamless substitute for Node.js, effectively reducing startup time and memory consumption. Bun stands out as an inventive JavaScript runtime, encompassing an integrated native bundler, transpiler, task runner, and a npm client. It is ingeniously designed to supplant traditional JavaScript and TypeScript scripts or applications on local machines. Notably, the latest release, version 5, introduces exciting additions such as npm workspaces, Bun.dns, and node:readline support.

[What is Bun](https://youtu.be/BsnCpESUEqM)

### Design goals

- **Performance**: Bun boasts a 4x faster startup time compared to Node.js.
- **TypeScript & JSX Capabilities**: Bun enables the direct execution of .jsx, .ts, and .tsx files, with its transpiler seamlessly converting them to vanilla JavaScript for execution.
- **ESM & CommonJS Compatibility**: While advocating for ES modules (ESM), Bun also supports CommonJS.
- **Web-Standard APIs**: Bun incorporates standard Web APIs like fetch, WebSocket, and ReadableStream.
- **Node.js Integration**: Bun not only supports Node-style module resolution but also aims for comprehensive compatibility with core Node.js globals and modules.

### Benchmarking
Bun distinguishes itself primarily through its exceptional speed, a minimum of 2.5 times faster than both Deno and Node.

Instead of relying on the typically faster V8 engine, Bun utilizes JavaScriptCore from WebKit. Furthermore, the creator of Bun has highlighted that ZIG, a low-level programming language akin to C or Rust, lacks hidden control flow, which significantly simplifies the development of fast applications.

![benchmarking](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgfvgcbi0iydcnox0fpi.png)

### Node vs Deno vs Bun
#### Node.js
Node.js, developed by Ryan Dahl and introduced in 2009, stands as the preeminent JavaScript runtime. In 2023, it garnered the top position as the most popular web technology according to Stack Overflow developers. Node.js has been a transformative force, expanding the horizons of JavaScript applications by enabling the creation of sophisticated backend-driven solutions. Today, it anchors a sprawling ecosystem replete with abundant resources and libraries.

#### Deno
Deno is a JavaScript runtime built on Rust, introduced by Ryan Dahl. It emerged with the aim of enhancing the features offered by Node.js. Deno places a strong emphasis on bolstering security compared to Node.js. It achieves this by mandating explicit permission for file, network, and environment access, thereby reducing the likelihood of common security vulnerabilities in these domains. Additionally, Deno is tailored to offer improved support for JSX and TypeScript, aligning more closely with web standards. Furthermore, it simplifies deployment by packaging applications as self-contained executables.

#### Bun
Bun, the latest contender in the runtime arena, is powered by Zig and positions itself as an all-inclusive runtime and toolkit, focusing on speed, bundling, testing, and compatibility with Node.js packages. Its standout feature lies in its exceptional performance, surpassing both Node.js and Deno.

A performance benchmark, exemplified by running an HTTP handler rendering a server-side React page, demonstrated that Bun handles approximately 68,000 requests per second, whereas Deno and Node.js manage around 29,000 and 14,000, respectively, showcasing a significant performance differential. Bun goes beyond performance, encompassing bundling and task-running capabilities for projects built with JavaScript and TypeScript. Similar to Deno, it delivers as single binaries and incorporates built-in support for Web APIs. Additionally, it extends support to select Node.js libraries, ensuring npm compatibility.

![comparison](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p0zeo6vennlxarvvwhgs.png)

### Installation
You have the flexibility to install Bun as a native package on any operating system, or alternatively, you can opt for a global NPM package installation. While it may seem unconventional to use NPM to its replacement, this approach undeniably streamlines the installation process.

```
# with install script (recommended)
curl -fsSL https://bun.sh/install | bash

# with npm
npm install -g bun

# with Homebrew
brew tap oven-sh/bun
brew install bun

# with Docker
docker pull oven/bun
docker run --rm --init --ulimit memlock=-1:-1 oven/bun
```
Bun requires unzip package to be installed, if you are using the curl option for installation.

```
sudo apt update
sudo apt-get install unzip
```
![installation1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0typ94nokbscgofcjb55.png)
![installation2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mm9brulu70ska70j7a04.png)
![installation3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzhl6ff03hu35b6vnw2v.png)

If you are using Windows machine, install WSL to run Bun.

Refer the following link to install WSL in your machine.

[Install Ubuntu on WSL2 and get started with graphical applications](https://ubuntu.com/tutorials/install-ubuntu-on-wsl2-on-windows-11-with-gui-support#1-overview)

You can do the installation by opening terminal with administrator privileges and executing the wsl — install command.

![installation4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/km3bwmvrm9xplfi14k59.png)
![Installation5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqqcvaagein7xlnqnwhj.png)

You can verify the bun installation using the following command,

```
bun --help
```
![Installation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghoe6q6bjdvgiw4srfo6.png)

### Experimenting with Bun
Let’s try some experiments with bun.

#### 1. Creating a simple HTTP server

Let’s create a simple HTTP server using the Bun.serve API.

- Create a project directory and switch to it.

```
mkdir http-server-demo
cd http-server-demo
```
- Run the following command on your terminal to scaffold a new project.

```
bun init
```
- Open index.ts and add the following code snippet to create a simple HTTP server using bun.

```
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello World");
  },
});
console.log(`Listening on http://localhost:${server.port}`);
```
- Execute the server using the following command,

```
bun run index.ts
```
You can open the url http://localhost:3000 in your browser to see the server response.

![output1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgpmgioqvzu8atpkjvol.png)
![output2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4i2pt11m8dtnbwggcalj.png)

#### 2. Creating a react application
Let’s create a react application using Bun’s vite support.

- Execute the following command to create a boilerplate for your react application using Bun.
```
bun create vite bun-react-demo
```
- Switch to the project directory and execute the following commands,
```
cd bun-react-demo
bun install
bun run dev
```
![output3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ia09v2dzo7t58hzt0yup.png)

You can view the output as follows,
![output4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8p9krtp3q1v80a0zv7vz.png)

#### 3. Bun for Next, Svelte, and Vue
For a Next.js application, Bun offers a comparable functionality initiated with the command: “bun create next ./app” In scenarios where an integrated loader isn’t present, Bun.js incorporates customizable loaders. These loaders enable the handling of files associated with frameworks like Svelte or Vue, such as .svelte or .vue extensions. Additionally, there’s an experimental SvelteKit adapter designed to run SvelteKit within the Bun environment.

### Bun Roadmap
The Bun roadmap encompasses numerous open tasks, offering a glimpse into the project’s extensive scope and ambitious goals. Bun aspires to evolve into a comprehensive solution, serving as a versatile platform for various server-side JavaScript tasks.

[Bun's Roadmap · Issue #159 · oven-sh/bun | github.com](https://github.com/oven-sh/bun/issues/159)

Thanks for reading this article.

Thanks Gowri M Bhatt for reviewing the content.

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!

The full source code for this tutorial can be found here,

[GitHub - codemaker2015/bun-demo: Experimenting with the new JavaScript framework | github.com](https://github.com/codemaker2015/bun-demo)

The article is also available on [Medium](https://codemaker2016.medium.com/bun-the-all-in-one-javascript-runtime-dc97721147a7).

### Useful Links

- [What is Bun, and does it live up to the hype? | byteofdev.com](https://byteofdev.com/posts/what-is-bun)
- [Bun - Incredibly fast JavaScript runtime | bestofjs.org](https://bestofjs.org/projects/bun)
- [Get Ubuntu from the Microsoft Store | apps.microsoft.com](https://apps.microsoft.com/store/detail/ubuntu/9PDXGNCFSCZV?hl=en-in&gl=in&rtc=1)