An Introduction to the Bun JavaScript Runtime — SitePoint

on

|

views

and

comments

[ad_1]

Bun is a rival JavaScript runtime to Node.js and Deno. On this article, we take take a look at Bun 1.0, and the explanations it could tempt you away out of your present favourite.

The unique model of this text was revealed in early 2023. Now that Bun model 1.0 has arrived, we overview whether or not this milestone could have any impression on the present JavaScript champions.

Desk of Contents

The Historical past: The place Bun Matches In with Node and Deno

Ryan Dahl launched Node.js in 2009. It wasn’t the primary server-side JavaScript runtime, however Node.js quickly gained momentum. Model 20 arrived in 2023, and Node.js has the most important improvement ecosystem, with 3.2 million modules — accounting for nearly 500 billion downloads per week (in keeping with npmjs.com).

In 2020, Ryan Dahl launched Deno — a remix of “noDe” — to modernize JavaScript improvement and deal with legacy points with Node.js safety, API compatibility, tooling, and module administration. Reception has been constructive, though Deno is but to problem Node’s domination.

In 2022, Jarred Sumner launched Bun following his frustrations with the velocity of Node.js when growing a Subsequent.js mission.

Bun makes use of the JavaScriptCore engine, which powers WebKit browsers reminiscent of Safari, relatively than the V8 engine utilized in Node.js, Deno, and Chrome.

The Bun runtime focuses on efficiency and developer expertise. The purpose is to eradicate slowness and complexity with out throwing away all the pieces that’s nice about JavaScript.

Bun can evolve sooner than Node.js — which should stay (principally) backward-compatible with the prevailing JavaScript and npm ecosystem.

Like Deno, Bun has native help for JavaScript and TypeScript with out requiring a third-party transpiler or configuration.

Bun is changing into a drop-in alternative for Node.js, Deno, serverless runtimes, construct, and testing instruments. It may substitute npm, npx, yarn, TypeScript compilers, dotenv, nodemon, pm2, Webpack, Babel, and Jest, to supply a whole all-in-one toolbox for growing purposes on a single platform.

The unique runtime was steady, however because of contributions from virtually 300 builders, the Bun model 1.0 launch arrived in September 2023. It will inevitably tempt extra builders emigrate to Bun the place they will benefit from the advantages described beneath.

What’s with the title “Bun”?

The origin of the “Bun” title is unclear, and the brand doesn’t assist! It might relate to the meals, fluffy bunny rabbits, “bundle”, or maybe it’s a brief, memorable title and the bun.sh area was accessible.

The Bun logo

Tasty Bun Advantages

Node.js and Deno use Chrome’s V8 JavaScript engine. Bun opts for the JavaScriptCore engine which powers WebKit browsers reminiscent of Safari. Bun itself is written in Zig — a low-level programming language with guide reminiscence administration and native threading to deal with concurrency. The result’s a light-weight runtime with a smaller reminiscence footprint, faster start-up instances, and efficiency which will be 4 instances sooner than Node.js and Deno beneath sure (benchmarking) circumstances.

Like Deno, Bun has native help for each JavaScript and TypeScript with out requiring a third-party transpiler or configuration. It additionally helps .jsx and .tsx recordsdata to transform HTML-like markup to native JavaScript. Experimental help for operating WebAssembly-compiled .wasm recordsdata is accessible.

Internally, Bun makes use of ES Modules, helps top-level await, interprets CommonJS, and implements Node’s node_modules decision algorithm. Bun caches modules in ~/.bun/set up/cache/ and makes use of hardlinks to copy them right into a mission’s node_modules listing. All tasks in your system will due to this fact reference a single occasion of the identical library, which reduces diskspace necessities and improves set up efficiency. (Word that macOS installations retain native variations for velocity.)

Bun helps Node’s bundle.json, npm equal instructions, and bunx — a npx-like choice to auto-install and run packages in a single command. For instance:

bunx cowsay "Whats up, world!"

bun init scaffolds empty tasks in the identical means as npm init, however you may as well template a brand new mission with bun create <template> <vacation spot>, the place <template> is an official bundle, a Github repository, or an area bundle. For instance, to create a brand new Subsequent.js mission:

bun create subsequent ./myapp

Bun features a bundler to import all dependencies right into a single file and may goal Bun, Node.js, and client-side JavaScript. This reduces the necessity to use instruments reminiscent of esbuild or Rollup:

bun construct ./index.ts —outdir ./out

Most command-line interface choices can be found through a JavaScript API, so it’s doable to create refined construct scripts with out a devoted process runner. Right here’s an equivalent construct to the command above:

await Bun.construct({
  entrypoints: ['./index.ts'],
  outdir: './out',
})

Bun has a regular check runner like Deno and Node.js 20. Operating bun check executes scripts named like this:

*.check.jsx
*_test.jsx
*.spec.jsx
*_spec.jsx

There’s no want for nodemon-like instruments, since bun has a —watch flag which restarts scripts or assessments once you modify a dependency file. Restarts are so quick that it turns into doable to live-reload on every keystroke. (Whether or not that is sensible and never a distraction is one other matter!)

Dwell reloading is just not fairly! (Warning: flickering content material!) View authentic animated GIF.

The same —sizzling mode is accessible, the place Bun watches for modifications and tender reloads modules. All recordsdata are re-evaluated, however the international state persists.

Atmosphere variables contained in mission .env recordsdata are mechanically loaded and parsed, making them accessible in Bun purposes, so there’s no want to make use of packages reminiscent of dotenv.

In addition to its personal Bun APIs for networking, file entry, baby processes, and so forth, Bun helps:

  • Net APIs reminiscent of fetch, URL, blob, WebSocket, JSON, setTimeout, and occasions.

  • Node.js compatibility APIs reminiscent of console, assert, dns, http, path, stream, and util, in addition to globals together with __dirname, and __filename. Bun claims that 90% of the most-used APIs are totally carried out, though you need to double-check these particular to your mission.

Lastly, Bun has a local SQLite3 shopper — bun:sqlite — which might cut back the variety of dependencies required in some tasks.

Putting in Bun

Bun is accessible as a single binary you’ll be able to set up on Linux, macOS, and Home windows WSL utilizing curl:

curl -fsSL https://bun.sh/set up | bash

It may be put in through the Node bundle supervisor:

npm set up -g bun

Or through Brew on macOS:

brew faucet oven-sh/bun
brew set up bun

Or through Docker:

docker pull oven/bun
docker run --rm --init --ulimit memlock=-1:-1 oven/bun

As soon as put in, you’ll be able to improve Bun utilizing:

bun improve

Or you’ll be able to uninstall Bun by eradicating the ~/.bun binary and cache listing:

rm -rf ~/.bun

Then replace your shell configuration file (.bashrc, .zshrc, or related) to take away ~/.bun/bin references from the $PATH variable.

Utilizing Bun

Bun is dependable in case you use it from the beginning of your mission. Pace is healthier than Node.js, though you’re unlikely to see a major efficiency enhance until your app is doing particular intensive duties such heavy SQLite processing or WebSocket messaging.

Node.js compatibility is nice for smaller, easier tasks, and I efficiently launched some scripts utilizing bun begin with out making modifications. Extra complicated purposes did fail, with obscure error messages generated deep within the node_modules hierarchy.

Bun vs Deno vs Node.js

Deno addressed lots of Node’s drawbacks, however builders didn’t essentially really feel compelled to modify:

  • Deno didn’t help Node’s third-party modules.
  • Migrating from Node.js to Deno required studying new strategies.
  • Whereas Deno provided a greater improvement expertise, Node.js was ok.

Deno has now added Node.js compatibility choices. That was the simplest technique to get builders to transition to Deno, however within the meantime, Node.js has adopted a few of Deno’s options, together with ES modules, a local check runner, and a —watch mode.

Bun has taken a unique strategy, aiming to be a quick, Node-compatible engine with Deno’s developments. The indicators are promising, nevertheless it’s not there but:

  • Efficiency is nice, however few builders complain about Node.js velocity.
  • Compatibility is nice, however it is going to be a problem to help all Node.js modules in a unique JavaScript engine. Can JavaScriptCore sustain with V8 developments with far much less funding?
  • Bun has the potential to interchange your tooling suite, nevertheless it’s but to supply the total vary present in Deno.

Compatibility of Bun with Node.js

Node.js compatibility is mostly good for smaller, easier tasks. You could possibly launch some scripts utilizing bun begin as an alternative of npm begin with out making any modifications.

Bun helps:

  • built-in Node.js modules and APIs reminiscent of fs, path, http, console, assert, and so forth
  • international variables and objects reminiscent of __dirname and course of
  • the Node.js module decision algorithm to find recordsdata in node_modules

Bun 1.0 claims to run “nearly any Node.js utility within the wild”. I’m but to be totally satisfied; complicated purposes can fail with obscure error messages generated deep inside your third-party modules.

ES Module and CommonJS Compatibility

Bun helps each ESM and CommonJS module techniques with top-level await. ESM took a number of years to reach in Node.js and the ecosystem continues to be dominated by CommonJS. With Bun, there’s no want for particular file extensions (.js, .cjs, .mjs) or "kind": "module" in bundle.json. You should utilize import or require() interchangeably in any file!

Internally, Bun interprets all modules to CommonJS and implements Node’s node_modules decision algorithm. Whether or not this works as anticipated is one other matter:

  • ES6 modules are pre-parsed to be able to resolve additional imports earlier than code is executed. Dynamic imports are doable, however ought to solely be thought of as a final resort.
  • CommonJS modules load dependencies on demand whereas executing the code. Dynamic imports are much less problematic.

Execution order will be essential in some purposes and it’s the explanation Node.js restricts you to EMS or CommonJS in a single file.

Net APIs

Bun has built-in help for Net customary APIs accessible in browsers, reminiscent of fetch, Request, Response, URL, blob, WebSocket, JSON, setTimeout, and ReadableStream. Deno launched these APIs to its server runtime and it makes net coding significantly extra constant. Node.js is catching up however options reminiscent of fetch arrived just lately in model 18.

Bun APIs

Bun ships with highly-optimized customary APIs for widespread operations reminiscent of file studying, file writing, HTTP serving, SQLite querying, and password hashing.

WebSockets are supported alongside HTTP with out requiring a third-party module reminiscent of ws:

Bun.serve({
  port: 8000,
  fetch(request) {
    return new Response('Whats up from the Bun server!');
  },
  websocket: {
    open(ws) { ... },
    message(ws, information) { ... },
    shut(ws, code, motive) { ... },
  }
});

TypeScript and JSX Assist

Like Deno, Bun has a JavaScript transpiler constructed into the runtime. You possibly can run JavaScript, TypeScript, JSX, or TSX recordsdata with out third-party dependencies. For instance:

bun index.ts
bun index.jsx
bun index.tsx

Bundle Administration

You should utilize Bun straight as an npm alternative in any Node.js mission. For instance:

bun set up
bun add <bundle> [--dev|--production|--peer]
bun take away <bundle>
bun replace <bundle>

Bun caches modules in ~/.bun/set up/cache/ and makes use of hardlinks to repeat them right into a mission’s node_modules listing. All tasks in your system due to this fact reference a single occasion of the identical library. This reduces disk house and improves set up efficiency by as much as an element of 30.

Dwell Reloading

There’s no want for nodemon-like instruments, for the reason that bun executable has a -watch flag to restart scripts or assessments once you modify a file.

The same —sizzling mode is accessible, the place Bun watches for modifications and tender reloads modules. All recordsdata are re-evaluated, however the international state persists.

Testing

Bun presents a Jest-compatible bun:check check runner with help for snapshot testing, mocking, and code protection. For instance:

import { check, anticipate } from "bun:check";

check('2 + 2', () => {
  anticipate(2 + 2).toBe(4);
});

Migration from Jest or Vitest is straightforward, since imports from @jest/globals or vitest are internally re-mapped to bun:check. It shouldn’t be essential to make code modifications.

Operating bun check executes scripts named:

*.check.jsx
*_test.jsx
*.spec.jsx
*_spec.jsx

Script Bundling

Bun is a JavaScript and TypeScript bundler and minifier which may goal code for the browser, Node.js, and different platforms. It’s impressed by esbuild and supplies a suitable plugin API:


Bun.construct({
  entrypoints: ['index.js'],
  outdir: 'construct'
});

Benchmarks illustrate Bun can twice as quick because the Go-compiled esbuild with related minification financial savings.

In contrast to esbuild, Bun doesn’t help CSS bundling, however that’s more likely to arrive given there’s a common plugin API…

Common Plugin API

Bun’s plugin API is common: it really works for each the bundler and the runtime. You possibly can outline plugins to intercept imports and carry out customized loading logic. This instance implements the import of .yaml recordsdata:

import { plugin } from "bun";

plugin({
  title: 'YAML',
  async setup(construct) {
    const { load } = await import('js-yaml');
    const { readFileSync } = await import('fs');
    construct.onLoad(yml)$/ , (args) => {
      const textual content = readFileSync(args.path, 'utf8');
      const exports = load(textual content) as File<string, any>;
      return { exports, loader: 'object' };
    });
  },
});

Begin-up and Execution Pace

Utilizing bun run <script> relatively than npm run <script> sometimes launches an utility 150ms sooner. That could be a small enchancment, however is’s 4x sooner than Node.js and noticeable once you’re operating many instructions and construct scripts. Efficiency enhancements will likely be higher when utilizing utilizing TypeScript, as a result of there’s no transpilation step.

Bun additionally makes the next Node.js efficiency claims:

  • 5x sooner than npx
  • 10x sooner at file reads (utilizing Bun.learn())
  • 3x sooner at file writes (utilizing Bun.write())
  • 4x sooner at serving HTTP requests (utilizing Bun.serve())
  • 4x sooner at SQLite queries (utilizing bun:sqlite)
  • 13x sooner than Jest when testing
  • 8x sooner than Vitest when testing

For bundling, Bun is:

  • virtually twice as quick as esbuild
  • 150x sooner than Parcel 2
  • 180x sooner than Rollup with Terser
  • 220x sooner than Webpack

You’re unlikely to see such good points throughout each mission, however Bun ought to enhance your improvement expertise.

Experimental Home windows Version

A local construct of Bun will likely be accessible for Home windows shortly. It’s extremely experimental and solely helps the JavaScript runtime with out efficiency optimizations. Options such because the bundle supervisor, check runner, and bundler have been disabled till they’re steady.

For the second, Home windows customers can set up Bun on the Home windows Subsystem for Linux — which stays the most suitable choice in case you’re doing any heavy JavaScript work.

Abstract: Ought to You Take a Chew from Bun?

Bun is an completed JavaScript runtime, however Node.js stays the champion for mission-critical tasks or legacy purposes. It’s best to attempt operating your app utilizing bun begin, however the bigger your codebase, the much less likelihood it would execute with out modification.

Deno might be a greater possibility than Bun for brand spanking new tasks, provided that it’s extra mature and feature-complete.

Bun is nice, and being actively developed, nevertheless it’s new. The runtime is steady, however few would wager on its long-term future at this stage. That stated, Bun has some fascinating concepts which I hope each the Node.js and Deno groups take into account adopting (CLI APIs and auto-loaded .env please!)

On a aspect be aware, I like Bun’s title, however it may be tough to seek for sources. ChatGPT makes the daring assertion that “There is no such thing as a extensively recognized JavaScript runtime known as ‘Bun’. So far as I’m conscious, there is no such thing as a such expertise within the JavaScript ecosystem.” This can be as a result of post-2021 information is proscribed, though sure questions return a Bun response and an apology for the error!

I think we’re heading towards an age of isomorphic server-side JavaScript, the place module builders try to put in writing code that’s suitable with all runtimes: Node.js, Deno, Bun, serverless, edge, embedded, and so forth. We could ultimately attain some extent the place JavaScript runtimes are principally interchangeable in the identical means browsers are at this time.

The Bun model 1.0 milestone could also be technically meaningless given the minor modifications from 0.8. The psychological distinction is larger: Bun feels extra full and usable. Extra builders will take into account the runtime and toolset for their very own tasks.

Deno initially went in its personal (good) route however needed to backtrack. It was too radical and too incompatible for a lot of Node.js builders. Switching from Node.js to Deno mid-project nonetheless isn’t one thing you need to ponder with out accepting the implications.

Bun has provided compatibility and velocity from the beginning — a substantial achievement given it’s utilizing a unique JavaScript engine. Whether or not it achieves one thing near 100% Node.js compatibility stays to be seen, however you might take into account it as a drop-in alternative for a few of your toolset on legacy tasks.

Bun’s velocity claims are spectacular, however few complain about uncooked Node.js efficiency, particularly when it improves with each launch. Some frameworks are sluggish, however that’s typically owing to bloat relatively than an inherent fault of the runtime.

For the second, Node.js stays the undisputed JavaScript champion. Few will get fired for selecting Node.js, however Bun has averted a few of Deno’s missteps and is quickly changing into a gorgeous possibility.

Ceaselessly Requested Questions on Bun, the JavaScript runtime

What’s Bun, and what does it do?

Bun is a JavaScript runtime that lets you execute JavaScript code outdoors of an online browser or Node.js surroundings. It supplies a light-weight and quick runtime for operating JavaScript purposes and is especially well-suited for serverless and cloud-native environments.

How does Bun differ from Node.js?

Bun is designed to be a light-weight and serverless-friendly runtime for JavaScript. It’s extra minimalistic and optimized for fast startup instances, making it a sensible choice for serverless capabilities and microservices. In distinction, Node.js is a extra complete runtime that features a bigger customary library.

What are the principle use instances for Bun?

Bun is especially well-suited for serverless computing, cloud capabilities, and microservices. It excels in eventualities the place quick startup instances and minimal useful resource utilization are essential, reminiscent of dealing with short-lived, event-driven duties within the cloud.

[ad_2]

Supply hyperlink

Share this
Tags

Must-read

Google Presents 3 Suggestions For Checking Technical web optimization Points

Google printed a video providing three ideas for utilizing search console to establish technical points that may be inflicting indexing or rating issues. Three...

A easy snapshot reveals how computational pictures can shock and alarm us

Whereas Tessa Coates was making an attempt on wedding ceremony clothes final month, she posted a seemingly easy snapshot of herself on Instagram...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here