introduce
Bun is a modern JavaScript runtime environment such as Node, Deno. The main features are as follows:
- Startup is fast.
- higher performance.
- Complete tools (packager, transcoder, package management).
Let's compare the performance of the framework mentioned below:
The number of operations per second in different js running environments under the same computer
More specific advantages
- Built-in APIs such as
fetch
,WebSocket
andReadableStream
- npm packages can be used in bun.js. ESM and CommonJS are supported, but Bun uses ESM internally.
- In bun.js, every file is transpiled. TypeScript & JSX can be used.
- bun supports "paths", "jsxImportSource" and more from the tsconfig.json file.
- Write, copy, pipe, send files using the fastest system calls provided by Bun.write.
- bun.js automatically loads environment variables from the .env file. require("dotenv").config() is no longer needed
- bun has a fast SQLite3 client built in bun:sqlite
- bun.js implements most of the Node-API (N-API). Many Node.js native modules work fine.
Loader
Currently, bun implements the following loaders:
Input | Loader | Output |
---|---|---|
.js | JSX + JavaScript | .js |
.jsx | JSX + JavaScript | .js |
.ts | TypeScript + JavaScript | .js |
.tsx | TypeScript + JSX + JavaScript | .js |
.mjs | JavaScript | .js |
.cjs | JavaScript | .js |
.mts | TypeScript | .js |
.cts | TypeScript | .js |
.toml | TOML | .js |
.css | CSS | .css |
.env | Env | N/A |
.* | file | string |
accomplish
Bun.js uses the JavaScriptCore engine,
It tends to perform faster than more traditional engines such as the V8.
And he himself is written in a language called Zig . Zig is a new system-level programming language, which is equivalent to an enhanced version of the C language.
configure
bunfig.toml
is the bun configuration file.
Here is an example:
# 默认框架
# 默认情况下,bun会寻找一个类似于`bun-framework-${framework}的npm包,然后是`${framework}`。
framework = "next"
logLevel = "debug"
# publicDir = "public"
# external = ["jquery"]
[macros]
# 像这样重新映射的配置:
# 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]
# 如果设置了`framework',就不需要这个了,在这里作为一个例子展示一下。
"@bigapp/design-system" = true
[dev]
# dev 的启动端口 3000-5000
port = 5000
[define]
# 环境变量
"process.env.bagel" = "'lox'"
[loaders]
# 如果文件后缀是 .bagel 则使用 JS 的解析器
".bagel" = "js"
[debug]
# 当导航到blob:或src:链接时,在你的编辑器中打开该文件
# 如果没有,它会尝试用$EDITOR或$VISUAL
# 如果仍然失败,它会尝试Visual Studio Code,然后是Sublime Text,然后是其他一些编辑器
# 这是由Bun.openInEditor()使用的
editor = "code"
# List of editors:
# - "subl", "sublime"
# - "vscode", "code"
# - "textmate", "mate"
# - "idea"
# - "webstorm"
# - "nvim", "neovim"
# - "vim","vi"
# - "emacs"
# - "atom"
use
First we download the cli
Execute the following command in the terminal to download:
curl https://bun.sh/install | bash
enable service
First try to implement related functions similar to node:
New file http.js
export default {
port: 3000,
fetch(request) {
return new Response("Welcome to Bun!");
},
};
Then execute in the terminal:
bun run http.js
Then open the browser address http://localhost:3000/
to view the return of the corresponding page Welcome to Bun!
If there is error handling in operation, it can be judged like this:
export default {
fetch(req) {
// if(...)
throw new Error("woops!");
},
error(error: Error) {
// 类似与 catch 到fetch 抛出的错误
return new Response("Uh oh!!\n" + error.toString(), { status: 500 });
},
}
Create project
Let's first try to use its default react template project to create:
bun create react ./app
The terminal section output after running the command:
The following directory will then appear:
In the project, you can run the command bun dev
This is his official react project template, of course it can be extended:
bun create github-user/repo-name destination
bun create local-example-or-remote-example destination
bun create /absolute/path/to-template-folder destination
bun create https://github.com/github-user/repo-name destination
bun create github.com/github-user/repo-name destination
Initialize the project by initializing the local path, github address, gitlab address
bun create workflow
When we run bun create ${template} ${destination}
, the following judgment will appear
Determine the remote template
- Request
registry.npmjs.org
Related path, download tgz - unzip, extract files
- Request
If it is GitHub
- Download via GitHub API
- Parse and extract files
If it is a local template
- Open local folder
- Empty files with existing names
- Copy files recursively
- Parse package, execute hook, download dependencies, initialize git
package management
bun 有他自己的包公里工具: bun install
, bunfig.toml
6181143de245bdf909c76a40776e4f5f---配置文件registry
, dev
, cache
etc.
bun install
Peer dependencies are handled similarly to yarn
. Peer dependencies will not be installed automatically, an attempt will be made to select an existing one.
lock file
bun.lockb
is the binary lock file format of bun
, as for why binary is chosen, the direct reason is for performance, and more storage
quick reason
It uses linear arrays for all data. Packages are referenced by an auto-incrementing integer ID or a hash of the package name. Strings longer than 8 characters are stripped.
Before being saved to disk, the lock files are ordered by garbage collection (GC) and traversing the package tree structure, and then the packages are downloaded according to their dependencies.
script runner
bun run
is a fast package.json
script runner
bun run ${script-name}
runs the equivalent of npm run script-name
. For example, bun run dev
runs the package.json
dev
script in ---d1b4f70cadd5aba7058ef9bd751af9ef---.
Running bun will automatically load environment variables from .env
55631e4326b171bfe88b5ee95b9eb401--- to shell/task
. .env
The load priority of the file is the same as the rest of the bun
:
- .env.local is loaded first
- if ($NODE_ENV === "production") .env.production else .env.development
- .env
If anything goes wrong, you can run bun run env
to get a list of environment variables.
question
currently existing problems
Zig's problem
Zig is a newer (2016) language, his ecology, security is worth considering
At the same time, if there is any problem at the bottom layer, there are very few people who know this language, it is easy to get stuck and be too passive.
Issue
There are currently 284 Issues (2022.07.27), some of which are particularly important and affect performance
ecological problem
Many commonly used and more important functions are not yet supported, such as:
- treeShaking
- Source maps
- Code splitting
- CSS compression
Details can be found here
Summarize
At present, the functions already possessed by bun cannot meet the normal production needs. We can only use it to try it out when developing some small tools.
Its structure, dedicated downloader, out-of-the-box use of TypeScript & JSX, built-in node API, etc. seem to be quite fragrant at present, and then there are also some of the problems I mentioned above.
The bun's cake is big and round, but we will wait and see if we can actually eat it in the future.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。