Bun Tutorial – Getting Started Guide With Examples

  • Mehul Mohan's profile image
    Mehul Mohan
    Team codedamn
Bun Tutorial – Getting Started Guide With Examples

Bun is a new JavaScript runtime released in 2022. It is a very interesting choice because a lot of “slow” parts of JavaScript runtime have been rewritten by Jarred Sumner (programmer behind Bun), which makes Bun extremely fast in a lot of scenarios.

Let us understand a few scenarios today for Bun – how you can use it and how it differs from Node.

Bun vs Node vs Deno

Bun, just like Node and Deno – is a JavaScript runtime. It focuses a lot more on speed, and Bun is trying to be compatible with Node (node_modules, node APIs, etc.)

Unlike deno and node, Bun is built on JavaScriptCore. Node and Deno use V8 as their primary JavaScript execution engines.

JavaScript engines at the end of the day are supposed to run JavaScript. Bun, however, comes with a lot of tooling baked in, a lot of speed and a bunch of convenient practices.

Bun Playground

I made a codedamn playground that uses a bunch of bun commands. Try it out here.

TypeScript support

The file typescript.ts simply shows that Bun can run TypeScript natively without any additional packages.

codedamn playground for bun

HTTP server with Bun

running HTTP playground in codedamn playground

The http.ts file shows how you can start an HTTP server with Bun. When started on port 1337, it automatically shows a preview on right, allowing you to build awesome projects with codedamn playgrounds.

JSX/TSX support

bun example of JSX support

Bun can easily work with JSX/TSX too. The file bun-jsx.tsx shows how you can easily console log a JSX element with bun.

Note that you need react package installed for JSX support to work.

bun start

Bun comes with a built-in manager to run npm scripts from package.json file. You can use bun start <script-name> and it will run the script.

The benefit of bun start is that it is up to 30x faster than npm according to official docs, and saves about 160ms on every run.

bun create

bun create is a way to bootstrap projects quickly, like React or Next.js boilerplates. Here’s an example for booting a Next.js project:

bun create next ./app
Code language: Bash (bash)

You can also create a project from a GitHub repo:

bun create mehulmpt/my-project ./app

You can try more bun commands from bun documentation and use codedamn for running the commands.