Bun

What are buns?

Bun is an all-in-one toolkit for JavaScript and TypeScript applications. It is distributed as a single executable named bun.

At the heart of Bun is the Bun Runtime, a fast JavaScript runtime designed to replace Node.js. It is written in the Zig language and powered by JavaScriptCore under the hood, greatly reducing startup time and memory usage.

bun run index.tsx   # TS and JSX supported out of the box

The bun command-line tool also implements a test runner, script runner, and Node.js-compatible package manager. It is faster than existing tools and can be used in existing Node.js projects with little modification.

bun run start                 # run the `start` script
bun install <pkg>             # install a package
bun build ./index.tsx         # bundle a project for browsers
bun test                      # run tests
bunx cowsay "Hello, world!"   # execute a package

what is runtime

JavaScript (or more formally, ECMAScript) is just a specification for a programming language. Anyone can write a JavaScript engine that takes a valid JavaScript program and executes it. The two most popular engines in use today are V8 (developed by Google) and JavaScriptCore (developed by Apple), both of which are open source.

Browsers

Most JavaScript programs don't run in isolation; they need to interact with the outside world to perform useful tasks. This is where the runtime comes in. The runtime provides additional APIs for use by JavaScript programs. It is important to note that the JavaScript runtime provided by the browser implements a set of web-specific APIs that are exposed through the global window object. Any JavaScript code executed in the browser can use these APIs to achieve interaction or dynamic behavior with the current web page context.

Node.js

Similarly, Node.js is a JavaScript runtime for use in non-browser environments such as servers. JavaScript programs executed via Node.js have access to a set of Node.js-specific global variables such as Buffer, process, and __dirname, as well as built-in modules for performing OS-level tasks such as reading and writing files (node:fs) and networking (node:net, node:http). In addition, Node.js also implements a CommonJS-based module system and parsing algorithm, which is earlier than JavaScript's native module system.

Bun was designed from the ground up to be a faster, leaner, and more modern Node.js alternative.

Some features of Bun

  • Speed  ​​- Currently, the Bun process starts up to 4x faster than Node.js

  • TypeScript and JSX support  - you can directly execute jsx, ts and tsx files, and Bun's transpiler converts these to plain JavaScript before execution.

  • ESM and CommonJS Compatibility  - The world is moving to ES Modules (ESM), but millions of packages on npm still require CommonJS. Bun recommends ES modules, but supports CommonJS.

  • web standard apis  - Bun implements standard web apis like fetch, WebSocket and ReadableStream. Bun is supported by the JavaScriptCore engine developed by Apple for Safari, so some APIs such as header and URL directly use the implementation of Safari.

  • node.js compatibility  - In addition to supporting node-style module parsing, Bun is fully compatible with built-in Node.js global variables (process, Buffer) and modules (path, fs, http, etc.) and other related work is in progress.

Bun is more than just a runtime. The long-term goal is to be a cohesive infrastructure toolkit for building applications with JavaScript/TypeScript, including package managers, transpilers, bundlers, script runners, test runners, and more.

#Get started

Write a simple HTTP server using the built-in Bun. Service APIs. First, create a new directory.

mkdir quickstart
cd quickstart

Run bun init to build a new project. When entering point, it will automatically match js or ts to generate configuration files correspondingly.

bun init
bun init helps you get started with a minimal project and tries to
# guess sensible defaults. Press ^C anytime to quit.

# package name (quickstart):
# entry point (index.ts):

# Done! A package.json file was saved in the current directory.
# + index.ts
# + .gitignore
# + tsconfig.json (for editor auto-complete)
# + README.md

# To get started, run:
# bun run index.ts

Open index.ts and type an http server.

const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(`Bun!`);
  },
});

console.log(`Listening on http://localhost:${server.port}...`);

Then start it.

bun index.ts

Same as node.js, very simple.

Support JSX, TSX, Text, JSON, TOML

Bun natively supports TypeScript out of the box. All files are dynamically compiled by Bun's fast native compiler before execution. Similar to other build tools, Bun does not perform type checking, it just removes type annotations from files.

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

JSX

react.tsx

function Component(props: {message: string}) {
  return (
    <body>
      <h1 style={
    
    {color: 'red'}}>{props.message}</h1>
    </body>
  );
}

console.log(<Component message="Hello world!" />);

Bun implements special logging for JSX to make debugging easier.

bun run react.tsx
// => <Component message="Hello world!" />

Yes, it is finally possible to debug a component in isolation.

Text

import text from "./text.txt";

console.log(text);
// => "Hello world!"

JSON and TOML

JSON and TOML files can be imported directly from source files, no difference.

import pkg from "./package.json";
import data from "./data.toml";

WASM

Experimental support for WASI (WebAssembly System Interface) since v0.5.2.

Custom Loader

For some file types not mentioned above, Bun supports extensions in the form of plugins.

Bun packaging tool

performance

Use the built-in bun .build() function or the bun build CLI command to build the front-end application.

Bun.build({
  entrypoints: ['./src/index.tsx'],
  outdir: './build',
  minify: true,
  // additional config
});
b4cd1183d0264c7489f0dc9b8d230658.png

Pack 10 copies of three.js, including sourcemaps and minification


In benchmarks (from esbuild's three.js benchmarks), Bun is 1.75 times faster than esbuild, 150 times faster than Parcel 2, 180 times faster than Rollup Terser, and 220 times faster than Webpack.

API

The goal of bun is to implement a minimal feature set, which is fast, stable, and suitable for most modern use cases without sacrificing performance, the API is as follows:

interface Bun {
  build(options: BuildOptions): Promise<BuildOutput>;
}

interface BuildOptions {
  entrypoints: string[]; // required
  outdir?: string; // default: no write (in-memory only)
  target?: "browser" | "bun" | "node"; // "browser"
  format?: "esm"; // later: "cjs" | "iife"
  splitting?: boolean; // default false
  plugins?: BunPlugin[]; // [] // see https://bun.sh/docs/bundler/plugins
  loader?: { [k in string]: string }; // see https://bun.sh/docs/bundler/loaders
  external?: string[]; // default []
  sourcemap?: "none" | "inline" | "external"; // default "none"
  root?: string; // default: computed from entrypoints
  publicPath?: string; // e.g. http://mydomain.com/
  naming?:
    | string // equivalent to naming.entry
    | { entry?: string; chunk?: string; asset?: string };
  minify?:
    | boolean // default false
    | { identifiers?: boolean; whitespace?: boolean; syntax?: boolean };
}

To quote Jarred Sumner, "Other packaging tools make poor architectural decisions in the pursuit of functional completeness that end up hurting performance, mistakes we carefully try to avoid".

module system

ES and Common are currently supported, ES is recommended, and others will be added in the future.

file type

The following file types are currently supported:.js .jsx .ts .tsx - JavaScript and TypeScript files. Duh..txt — Plain text files. These are inlined as strings..json .toml — These are parsed at compile time and inlined as JSON.


Everything else is considered a static resource. Static resources are copied into outdir as-is, and imports are replaced with relative paths or URLs to files, eg /images/logo.png.

input:

import logo from "./images/logo.png";

output:

var logo = "./images/logo.png";

Plugins

Like the runtime itself, the bundler is designed to be extensible through plugins. In fact, there is no difference between runtime plugins and bundler plugins.

import YamlPlugin from "bun-plugin-yaml";

const plugin = YamlPlugin();

// register a runtime plugin
Bun.plugin(plugin);

// register a bundler plugin
Bun.build({
  entrypoints: ["./src/index.ts"],
  plugins: [plugin],
});

There are also some "standard configurations" of modern packaging tools, such as Tree shaking, Source maps, etc., which are also supported by Bun.

Finally, the space is limited, so I won’t introduce too much about other aspects. Interested friends, you can check the official website by yourself.

Official website: https://bun.sh/

Guess you like

Origin blog.csdn.net/qiwoo_weekly/article/details/131650909
Bun