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


  1. Server-side rendering of React: HTTP requests per second

  2.  Loading a large data table: average queries per second

  3.  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?

  1.  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 .

  1.  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;

  1.  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 for fetch、WebSocket、 ReadableStream and API ;

  • Node.js Modules: Bun implements the module parsing algorithm of Node.js so that we can use npm packages in Bun with support for both ESM and CommonJS , but Bun uses ESM internally;

  • Bun.js Implemented most of the Node-API ( N-API ), most of the Node.js native modules and global variables (such as Buffer and process) work fine;

  • Automatically loads the environment variable .env file without the need for require("dotenv").load() ;

  • Comes with a built-in quick SQLite3 client bun: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

  1.  curl https://bun.sh/install | bash
    
  2.  New http.js

     export default {
       port: 3000,
       fetch(request) {
         return new Response('Welcome to Bun!');
       },
     };
    
  3.  bun run http.js
    

  4. 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

  1.  Install dependencies via package.json

     bun install
    

  2. Adds or removes an installation package from package.json.

     
     bun remove react
     
     
     bun add preact
    


According to tests, on Linux bun install tends to run installers 20 – 100 times faster than npm install runs scripts.

 2. Run the scripts script directly


  1. Use bun run instead npm run

     # Instead of "npm run clean"
     bun run clean
     
     # This also works
     bun clean
    
  2.  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 runs package.json scripts 30 times faster than npm runs package.json scripts.


3. Quickly create a Next.js project

  1.  Quick Creation

     
     bun create next ./app
     
     
     cd app
     bun dev # start dev server
    
  2.  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

  1.  Quick Creation

     bun create react ./app
     cd app
     bun dev # start dev server
    
  2.  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 to yarn add or npm install

  • bun install: equivalent to yarn install or npm 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 the node_modules.bun file containing this information

  • bun upgrade: To upgrade bun, run bun 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 of framework to be used by default. bun will look for the npm package based on the bun-framework-${framework} format;


  • logLevel : Specifies the log level (available values error , warn , info , and debug );


  • publicDir : Specifies the public directory;


  • external : Specifies external extensions, equivalent to Webpack externals;


  • macros : Macro definition to replace the import path, e.g.: import { graphql } from 'react-relay' ; will be converted to import { graphql } from "macro:bun-macro-relay/bun-macro-relay.tsx" ;


  • dev.port : Specifies the listening port for the service (default 3000 );


  • 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)

By lzz

Leave a Reply

Your email address will not be published. Required fields are marked *