What is it, Bun?
Bun (pronounced similarly to [bʌn], meaning bun) is a modern JavaScript
like Node or Deno ;
In layman’s terms, it means you can run JavaScript code on the Bun. Aren’t you thinking that it’s the same as Node and Deno, and it’s also hot?
Don’t worry, we’ll see;
all-in-one
It’s also officially known as: all-in-one JavaScript runtime
;
all in one
because Bun is different from traditional Node.js, which is traditionally javaScript
; Bun provides the functionality of , with a built-in native bundler, translator, task runner, npm client, and hundreds of Node.js APIs and Web APIs, including about 90% of the Node-API functions (native modules), fs, path, Buffer, and more.
This means that you can implement most of the Node APIs and Web APIs that run on the Bun, and you can also run TypeScript 、JSX
without having to use tools like Webpack、Rollup、esbuild、babel
;
At first glance, isn’t it instantly classier?
But that’s not enough to blow it in front of your coworkers and interviewers 🐂 🍺
Ladies and gentlemen, you continue reading…
Why Bun?
Performance Test Results
Server-side rendering of React: HTTP requests per secondLoading a large data table: average queries per second
FFI: operations per second
Based on the above FFI
comparison, we can see that Bun can be said to beat Node.js and Deno in terms of performance;
Why?
- Engine Differences
Unlike Node.js and Deno, Bun is not based on the V8
engine, but instead uses the JavaScriptCore engine, which tends to execute faster than more traditional engines like V8
.
- language difference
Bun.js
Written in ZIG, an emerging systems programming language, it focuses on improving program performance through finer-grained control of memory through manual memory management, with no hidden control flow;
- scratch
With the above two points in mind, much of Bun.js
was written completely from scratch, including the JSX/TypeScript
translator, npm
client, packager, SQLite
client, HTTP
client, WebSocket
client, and so on.
Note: Zig is a system-level programming language designed for stability, maintainability, and performance, and is seeking to replace C as the best in system programming.
Built-in compatibility
Web API support: Built-in support is provided forfetch、WebSocket、 ReadableStream
andAPI
;
Node.js Modules:Bun
implements the module parsing algorithm ofNode.js
so that we can use npm packages in Bun with support for bothESM
andCommonJS
, butBun
usesESM
internally;
Bun.js
Implemented most of theNode-API
(N-API
), most of theNode.js
native modules and global variables (such as Buffer and process) work fine;
Automatically loads the environment variable.env
file without the need forrequire("dotenv").load()
;
Comes with a built-in quickSQLite3
clientbun:sqlite
;
Built-in JavaScript, TypeScript, JSX, etc. (see table below) translators; Input | Loader | Output | | —– | —————————– | —— | | .js | JSX + JavaScript | .js | | .jsx | .tsx | TypeScript + JavaScript | .js | .tsx | TypeScript + JSX + JavaScript | . jsx | JSX + JavaScript | .js | | .ts | TypeScript + JavaScript | .js | | .tsx | TypeScript + JSX + JavaScript | . js | | .mts | TypeScript | .js | | .cts | TypeScript | .js | | .toml | TOML | .js | | .css | CSS | .css | .env | Env | N/A | | . * | file | string |
As you can see from the above, Bun’s goal is to run JavaScript outside of the browser, to bring performance and complexity enhancements to our infrastructure, and to increase developer productivity with better, simpler tools.
Getting Started
Installation on Mac/Linux
curl https://bun.sh/install | bash
New http.js
export default { port: 3000, fetch(request) { return new Response('Welcome to Bun!'); }, };
bun run http.js
Just open it in your browser: http://localhost:3000
Note: If you are using Linux, kernel version 5.6 or higher is highly recommended, but 5.1 is the minimum.
Installation on windows
Since Bun is not very friendly to windows users, it is not easy to install, if you really want to install it on windows, you can check out this article on how to install Bun on windows to install it;
Common Functions of Bun
1. Use as a package manager
Install dependencies via package.json
bun install
Adds or removes an installation package from package.json.bun remove react bun add preact
According to tests, on Linuxbun install
tends to run installers 20 – 100 times faster thannpm install
runs scripts.
2. Run the scripts
script directly
Usebun run
insteadnpm run
# Instead of "npm run clean" bun run clean # This also works bun clean
Run the script from
package.json
# package.json { "name": "myapp", "scripts": { "clean": "rm -rf dist out node_modules" } } bun run clean
According to tests,bun
runspackage.json
scripts 30 times faster thannpm
runspackage.json
scripts.
3. Quickly create a Next.js project
Quick Creation
bun create next ./app cd app bun dev # start dev server
Associating an existing Next.js application
bun add bun-framework-next echo "framework = 'next'" > bunfig.toml bun bun # bundle dependencies bun dev # start dev server
Note: Next.js supports all the necessary functions, but there are also a few that are not supported at the moment, so you need to be careful when using the generated environment.
4. Quickly create a React project
Quick Creation
bun create react ./app cd app bun dev # start dev server
Associate an existing React project
# To enable React Fast Refresh, ensure it is installed bun add -d react-refresh # Generate a bundle for your entry point(s) bun bun ./src/index.js # jsx, tsx, ts also work. can be multiple files # Start the dev server bun dev
5. Run TypeScript
Running Run TypeScript is naturally supported in Bun
with no configuration and no additional installation required;
If you import a .ts
or .tsx
file, bun will convert it to JavaScript; bun also compiles .ts
or .tsx
files from node_modules
; this is due to bun’s built-in TypeScript compiler, which is very fast.
If you want to use the API globally, install bun-typs
into your project.
bun add -d bun-types
{
"compilerOptions": {
"types": ["bun-types"]
}
}
6. Common commands
bun add: equivalent toyarn add
ornpm install
bun install: equivalent toyarn install
ornpm install
- bun run: similar to
npm run
bun create: This command allows you to quickly create a template project.
bun bun: This command recursively collects the import dependencies for the specified file and generates thenode_modules.bun
file containing this information
bun upgrade: To upgrade bun, runbun upgrade
7. Configuration files bunfig.toml
bunfig.toml
is the configuration file for bun.
It allows you to load the configuration at bunfig.toml
instead of passing arguments to the command line each time. Loading the configuration file before parsing the command line arguments means that the command line arguments can override this configuration.
Below is an example configuration:
# Set a default framework to use
# By default, bun will look for an npm package like `bun-framework-${framework}`, followed by `${framework}`
framework = "next"
logLevel = "debug"
# publicDir = "public"
# external = ["jquery"]
[macros]
# Remap any import like this:
# import {graphql} from 'react-relay';
# To:
# import {graphql} from 'macro:bun-macro-relay';
react-relay = { "graphql" = "bun-macro-relay" }
[bundle]
saveTo = "node_modules.bun"
# Don't need this if `framework` is set, but showing it here as an example anyway
entryPoints = ["./app/index.ts"]
[bundle.packages]
# If you're bundling packages that do not actually live in a `node_modules` folder or do not have the full package name in the file path, you can pass this to bundle them anyway
"@bigapp/design-system" = true
[dev]
# Change the default port from 3000 to 5000
# Also inherited by Bun.serve
port = 5000
[define]
# Replace any usage of "process.env.bagel" with the string `lox`.
# The values are parsed as JSON, except single-quoted strings are supported and `'undefined'` becomes `undefined` in JS.
# This will probably change in a future release to be just regular TOML instead. It is a holdover from the CLI argument parsing.
"process.env.bagel" = "'lox'"
[loaders]
# When loading a .bagel file, run the JS parser
".bagel" = "js"
[debug]
# When navigating to a blob: or src: link, open the file in your editor
# If not, it tries $EDITOR or $VISUAL
# If that still fails, it will try Visual Studio Code, then Sublime Text, then a few others
# This is used by Bun.openInEditor()
editor = "code"
# List of editors:
# - "subl", "sublime"
# - "vscode", "code"
# - "textmate", "mate"
# - "idea"
# - "webstorm"
# - "nvim", "neovim"
# - "vim","vi"
# - "emacs"
# - "atom"
# If you pass it a file path, it will open with the file path instead
# It will recognize non-GUI editors, but I don't think it will work yet
Related Properties Explained:
framework
: Specify the version offramework
to be used by default. bun will look for thenpm
package based on thebun-framework-${framework}
format;
logLevel
: Specifies thelog
level (available valueserror
,warn
,info
, anddebug
);
publicDir
: Specifies thepublic
directory;
external
: Specifies external extensions, equivalent to Webpack externals;
macros
: Macro definition to replace theimport
path, e.g.:import { graphql } from 'react-relay'
; will be converted toimport { graphql } from "macro:bun-macro-relay/bun-macro-relay.tsx"
;
dev.port
: Specifies the listening port for the service (default3000
);
define
: This is equivalent to Webpack’s DefinePlugin;loaders
: Specify the parser for each type of file;
Of course, the above is just an example of some common cases in the front-end field, if you still want to learn more about the use of methods and cases, you can check out:
See the official example: Link
View the official documentation: Link
About Bun Author
Author Jarred Sumner dropped out of high school and worked at Stripe and Thiel Fellowship;
The author of the single output ability is very strong, in order to become a veritable volume of the king, from April 2021 initial submission so far there have been more than a million lines of code additions and deletions, a single person to complete more than 98% of the amount of submissions, personally known as the volume in the volume of the king, the king of the king, a king is more than a king of the king of the strong. (I’m just trying to have fun, I don’t mean anything else, please don’t spray)