![An Introduction to the Bun JavaScript Runtime — SitePoint An Introduction to the Bun JavaScript Runtime — SitePoint](https://techtoguide.com/wp-content/uploads/2023/11/An-Introduction-to-the-Bun-JavaScript-Runtime-—-SitePoint-768x435.jpg)
[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 influence on the present JavaScript champions.
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 biggest growth ecosystem, with 3.2 million modules — accounting for nearly 500 billion downloads per week (based on npmjs.com).
In 2020, Ryan Dahl launched Deno — a remix of “noDe” — to modernize JavaScript growth and handle legacy points with Node.js safety, API compatibility, tooling, and module administration. Reception has been optimistic, 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 creating a Subsequent.js venture.
Bun makes use of the JavaScriptCore engine, which powers WebKit browsers reminiscent of Safari, quite than the V8 engine utilized in Node.js, Deno, and Chrome.
The Bun runtime focuses on efficiency and developer expertise. The goal is to get rid of slowness and complexity with out throwing away the whole lot that’s nice about JavaScript.
Bun can evolve quicker than Node.js — which should stay (principally) backward-compatible with the present 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 turning into a drop-in alternative for Node.js, Deno, serverless runtimes, construct, and testing instruments. It could actually change npm
, npx
, yarn
, TypeScript compilers, dotenv, nodemon, pm2, Webpack, Babel, and Jest, to supply an entire all-in-one toolbox for creating purposes on a single platform.
The unique runtime was steady, however due to contributions from virtually 300 builders, the Bun model 1.0 launch arrived in September 2023. This can inevitably tempt extra builders emigrate to Bun the place they’ll benefit from the advantages described under.
What’s with the identify “Bun”?
The origin of the “Bun” identify is unclear, and the emblem doesn’t assist! It may relate to the meals, fluffy bunny rabbits, “bundle”, or maybe it’s a brief, memorable identify and the bun.sh area was accessible.
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 handbook 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 may be 4 instances quicker than Node.js and Deno underneath 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 working WebAssembly-compiled .wasm recordsdata is offered.
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 venture’s node_modules
listing. All initiatives in your system will subsequently reference a single occasion of the identical library, which reduces diskspace necessities and improves set up efficiency. (Be aware 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 "Howdy, world!"
bun init
scaffolds empty initiatives in the identical means as npm init
, however you may as well template a brand new venture 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 venture:
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 attainable to create refined construct scripts and not using a devoted activity runner. Right here’s an equivalent construct to the command above:
await Bun.construct({
entrypoints: ['./index.ts'],
outdir: './out',
})
Bun has a normal take a look at runner like Deno and Node.js 20. Working bun take a look at
executes scripts named like this:
*.take a look at.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 checks whenever you modify a dependency file. Restarts are so quick that it turns into attainable to live-reload on every keystroke. (Whether or not that is sensible and never a distraction is one other matter!)
Stay reloading is just not fairly! (Warning: flickering content material!) View unique animated GIF.
An identical —sizzling
mode is offered, the place Bun watches for adjustments and delicate reloads modules. All recordsdata are re-evaluated, however the world state persists.
Atmosphere variables contained in venture .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:
-
Internet APIs reminiscent of
fetch
,URL
,blob
,WebSocket
,JSON
,setTimeout
, and occasions. -
Node.js compatibility APIs reminiscent of
console
,assert
,dns
,http
,path
,stream
, andutil
, in addition to globals together with__dirname
, and__filename
. Bun claims that 90% of the most-used APIs are absolutely carried out, though you must double-check these particular to your venture.
Lastly, Bun has a local SQLite3 consumer — bun:sqlite — which may cut back the variety of dependencies required in some initiatives.
Putting in Bun
Bun is offered 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 the event you use it from the beginning of your venture. Velocity is healthier than Node.js, though you’re unlikely to see a major efficiency enhance except your app is doing particular intensive duties such heavy SQLite processing or WebSocket messaging.
Node.js compatibility is nice for smaller, easier initiatives, and I efficiently launched some scripts utilizing bun begin
with out making adjustments. 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 growth expertise, Node.js was ok.
Deno has now added Node.js compatibility choices. That was the best approach 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 take a look at runner, and a —watch
mode.
Bun has taken a unique method, 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 will probably 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 exchange your tooling suite, nevertheless it’s but to supply the complete vary present in Deno.
Compatibility of Bun with Node.js
Node.js compatibility is usually good for smaller, easier initiatives. You could possibly launch some scripts utilizing bun begin
as a substitute of npm begin
with out making any adjustments.
Bun helps:
- built-in Node.js modules and APIs reminiscent of
fs
,path
,http
,console
,assert
, and so forth - world variables and objects reminiscent of
__dirname
andcourse 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 absolutely 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 methods with top-level await
. ESM took a number of years to reach in Node.js and the ecosystem remains 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 use 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 so as to resolve additional imports earlier than code is executed. Dynamic imports are attainable, 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 may be important in some purposes and it’s the rationale Node.js restricts you to EMS or CommonJS in a single file.
Internet APIs
Bun has built-in help for Internet 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 not too long ago 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('Howdy from the Bun server!');
},
websocket: {
open(ws) { ... },
message(ws, knowledge) { ... },
shut(ws, code, purpose) { ... },
}
});
TypeScript and JSX Help
Like Deno, Bun has a JavaScript transpiler constructed into the runtime. You’ll be able to 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 use Bun straight as an npm
alternative in any Node.js venture. 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 venture’s node_modules
listing. All initiatives in your system subsequently 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.
Stay Reloading
There’s no want for nodemon-like instruments, for the reason that bun
executable has a -watch
flag to restart scripts or checks whenever you modify a file.
An identical —sizzling
mode is offered, the place Bun watches for adjustments and delicate reloads modules. All recordsdata are re-evaluated, however the world state persists.
Testing
Bun presents a Jest-compatible bun:take a look at
take a look at runner with help for snapshot testing, mocking, and code protection. For instance:
import { take a look at, count on } from "bun:take a look at";
take a look at('2 + 2', () => {
count on(2 + 2).toBe(4);
});
Migration from Jest or Vitest is straightforward, since imports from @jest/globals
or vitest
are internally re-mapped to bun:take a look at
. It shouldn’t be essential to make code adjustments.
Working bun take a look at
executes scripts named:
*.take a look at.tsx
*_test.tsx
*.spec.tsx
*_spec.tsx
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 appropriate 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 prone 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’ll be able to outline plugins to intercept imports and carry out customized loading logic. This instance implements the import of .yaml
recordsdata:
import { plugin } from "bun";
plugin({
identify: '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 Document<string, any>;
return { exports, loader: 'object' };
});
},
});
Begin-up and Execution Velocity
Utilizing bun run <script>
quite than npm run <script>
sometimes launches an utility 150ms quicker. That could be a small enchancment, however is’s 4x quicker than Node.js and noticeable whenever you’re working many instructions and construct scripts. Efficiency enhancements shall 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 quicker than
npx
- 10x quicker at file reads (utilizing
Bun.learn()
) - 3x quicker at file writes (utilizing
Bun.write()
) - 4x quicker at serving HTTP requests (utilizing
Bun.serve()
) - 4x quicker at SQLite queries (utilizing
bun:sqlite
) - 13x quicker than Jest when testing
- 8x quicker than Vitest when testing
For bundling, Bun is:
- virtually twice as quick as esbuild
- 150x quicker than Parcel 2
- 180x quicker than Rollup with Terser
- 220x quicker than Webpack
You’re unlikely to see such positive aspects throughout each venture, however Bun ought to enhance your growth expertise.
Experimental Home windows Version
A local construct of Bun shall 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, take a look at 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 the event you’re doing any heavy JavaScript work.
Abstract: Ought to You Take a Chunk from Bun?
Bun is an completed JavaScript runtime, however Node.js stays the champion for mission-critical initiatives or legacy purposes. You must strive working your app utilizing bun begin
, however the bigger your codebase, the much less probability it is going to execute with out modification.
Deno might be a greater possibility than Bun for brand new initiatives, 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 contemplate adopting (CLI APIs and auto-loaded .env
please!)
On a aspect notice, I like Bun’s identify, however it may be tough to seek for assets. ChatGPT makes the daring assertion that “There isn’t 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 knowledge is restricted, though sure questions return a Bun response and an apology for the error!
I believe we’re heading towards an age of isomorphic server-side JavaScript, the place module builders try to jot down code that’s appropriate with all runtimes: Node.js, Deno, Bun, serverless, edge, embedded, and so forth. We could ultimately attain a degree the place JavaScript runtimes are principally interchangeable in the identical means browsers are as we speak.
The Bun model 1.0 milestone could also be technically meaningless given the minor adjustments from 0.8. The psychological distinction is bigger: Bun feels extra full and usable. Extra builders will contemplate the runtime and toolset for their very own initiatives.
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 must 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 would contemplate it as a drop-in alternative for a few of your toolset on legacy initiatives.
Bun’s velocity claims are spectacular, however few complain about uncooked Node.js efficiency, particularly when it improves with each launch. Some frameworks are gradual, however that’s usually owing to bloat quite 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 prevented a few of Deno’s missteps and is quickly turning into a horny possibility.
Steadily Requested Questions on Bun, the JavaScript runtime
Bun is a JavaScript runtime that permits you to execute JavaScript code exterior of an online browser or Node.js setting. It supplies a light-weight and quick runtime for working JavaScript purposes and is especially well-suited for serverless and cloud-native environments.
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 good selection for serverless features and microservices. In distinction, Node.js is a extra complete runtime that features a bigger customary library.
Bun is especially well-suited for serverless computing, cloud features, and microservices. It excels in situations the place quick startup instances and minimal useful resource utilization are important, reminiscent of dealing with short-lived, event-driven duties within the cloud.
[ad_2]