はじめに
webエンジニアの風速です。
今回は前から聞いたことのあった、Bunを触ってみようと思います。
Bunとは
安定版がリリースされたのは2023年の9月で、JavaScriptおよびTypeScriptアプリ用のall-in-one toolkitで、そのなかでもメインがNode.jsの代替として設計された高速JavaScriptランタイムです。他にもテストランナー、スクリプトランナー、Node.js互換パッケージマネージャーなどの機能があります。
インストール
今回はmac OSを使用するので、brewでインストールします。
$ brew install bun
$ bun --version
1.1.26
クイックスタートを試してみる
テストプロジェクトの作成
ディレクトリ作成
$ mkdir bun-test
$ cd bun-test
プロジェクトの作成
プロジェクトを作成します。対話ツールが起動されます。
今回は全てEnterで進めました。
$ bun init
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 (bun-test):
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
以下のような構成でファイルが生成されています。
$ ls -1
README.md
bun.lockb
index.ts
node_modules
package.json
tsconfig.json
ファイル実行
bun init
でプロジェクトが作成されたので、index.tsを編集します。
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Bun!");
},
});
console.log(`Listening on http://localhost:${server.port} ...`);
index.tsの実行をします。
$ bun index.ts
Listening on http://localhost:3000 ...
localhostを叩くと以下のようにレスポンスが返ってきます。
$ curl http://localhost:3000
Bun!
Node.jsではTypeScriptファイルを実行するには、ts-nodeなどを用いる必要がありますが、BunではTypeScriptがサポートされているので、そのまま実行できます。
Node.jsでは実験的にサポートが始まっている。
scriptの実行
package.jsonに以下を追記します。
{
"name": "quickstart",
"module": "index.ts",
"type": "module",
+ "scripts": {
+ "start": "bun run index.ts"
+ },
"devDependencies": {
"@types/bun": "^1.0.0"
}
}
$ bun run start
$ bun run index.ts
Listening on http://localhost:3000 ...
パッケージのインストール
$ bun add figlet
$ bun add -d @types/figlet #tsを使用する場合は型宣言もインストール
index.tsを以下のように編集する。
+ import figlet from "figlet";
const server = Bun.serve({
port: 3000,
fetch(req) {
+ const body = figlet.textSync("Bun!");
+ return new Response(body);
- return new Response("Bun!");
},
});
localhostを叩くと以下のようにレスポンスが返ってきます。
$ curl http://localhost:3000
____ _
| __ ) _ _ _ __ | |
| _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)
まとめ
自分はjsのランタイム自体はNode.jsしか使用したことがなかったのですが、Node.jsやnpmとも互換があり、使用感はあまり変わらないと感じました。今回さわったクイックスタートでは速度の違いには言及できませんでしたが、そのあたりも検証などできたら良いかなと思います。個人的にはDenoも名前がかわいくて気になっているので、機会があればさわってみたいと思います。🦖
参考