[[Windows 11]]のホストマシンで、[[VM]]の[[Ubuntu]]を使って[[Bun]]を動かしてみた話。 ## VMの起動 [[Multipass]]を使う。既に作成済のイメージがあるのでログイン。 ```console multipass exec ubuntu-sandbox -- bash ``` ## [[Deno]]のインストール [[asdf]]でインストールする。 ```console asdf plugin add deno asdf install deno latest asdf global deno latest ``` ## [[Bun]]のインストール [[asdf]]でインストールする。 ```console asdf plugin add bun asdf install bun latest asdf global bun latest ``` ## インストールの速さを体験する [[🦉Miroir]]をインストールしてみる。 ```console git clone https://github.com/tadashi-aikawa/miroir.git ``` ```console bun install ``` 公称:12.13s、感覚20秒弱。 2回目は8秒かからないくらい。 ### [[npm]]でもインストール 公称:3分 (180s)、感覚2分30秒 (150s)。 少なくとも10倍は速そう。 ## プロジェクトを作ってみる ```console $ mkdir bun-sandbox $ cd bun-sandbox $ bun init -y Done! A package.json file was saved in the current directory. + index.ts + .gitignore + tsconfig.json (for editor auto-complete) + README.md ``` 一式ができる。ついでにGitリポジトリとして初期化しておく。 ```console git init ``` 全然気づかなかったけど、いつの間にか[[node_modules]]ができてた。[[Bun]]の型定義っぽい。 ```console $ tree node_modules/  node_modules └──  bun-types ├──  package.json ├──  README.md ├──  tsconfig.json └──  types.d.ts ``` ## プロジェクトを実行してみる 実行してみる。 ```console $ bun index.ts Hello via Bun! ``` `--watch`フラグを付けると、変更があったときに再実行される。調べものをするときは便利。 ```console bun --watch index.ts ``` ## [[npmパッケージ]]をインストールしてみる [[Deno]]と違って[[Bun]]は[[Node.js]]に近い体験を提供していると思うので試してみる。ライブラリとしては[[Lodash]]を使ってみる。 ```ts bun i lodash bun i -D @types/lodash ``` 相変わらずインストールが速い。コードを書いてみる。 ```ts import _ from "lodash"; interface Human { id: number; name: string; } const users = [ { id: 1, name: "Ichiro" }, { id: 2, name: "Jiro" }, { id: 3, name: "Saburo" }, { id: 4, name: "Shiro" }, { id: 5, name: "Goro" }, ] satisfies Human[]; const oddUserNames = _(users) .filter((x) => x.id % 2 !== 0) .map((x) => x.name) .value(); console.log(oddUserNames); // [ "Ichiro", "Saburo", "Goro" ] ``` 何事もなく動いた。 ## コマンドライン引数に適応 ライブラリを使わずに[[コマンドライン引数]]を取得して処理するようにしてみる。 ```ts import { argv } from "bun"; import { error, log } from "console"; import _ from "lodash"; import { exit } from "process"; const [message, countStr] = argv.slice(2); if (!message) { error("第1引数にはメッセージを指定してください"); exit(1); } const count = Number(countStr); if (isNaN(count)) { error("第2引数には数値を指定してください"); exit(1); } if (count <= 0) { error("第2引数には1以上の整数を指定してください"); exit(1); } const result = _(new Array(count)).fill(message).join("\n"); log(result); ``` ```console $ bun index.ts hoge 3 hoge hoge hoge ``` ## ビルド シングルバイナリにビルドする。 ```console $ bun build --compile index.ts --outfile=bunbun [7ms] bundle 2 modules [35ms] compile bunbun ``` コンパイルは一瞬。バイナリサイズは約100Mとデカイ。 ```console $ ll | grep bunbun .rwxrwxrwx 96M ubuntu 18 Sep 23:13 -N  bunbun ```