Nuxt のアプリを nexe でシングルバイナリにしたいという方が居たので、 試しにやってみた。
Nuxt アプリケーションの作成
プロジェクトの初期化
vscode ➜ .../TIL/js/nuxtjs/firststep (master) $ npx nuxi@latest init firststep
Need to install the following packages:
nuxi@3.20.0
Ok to proceed? (y) y
✔ Which package manager would you like to use?
npm
◐ Installing dependencies...
npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported
> postinstall
> nuxt prepare
✔ Types generated in .nuxt
added 671 packages, and audited 673 packages in 1m
130 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
✔ Installation completed.
✔ Initialize git repository?
No
✨ Nuxt project has been created with the v3 template. Next steps:
› cd firststep
› Start development server with npm run dev
npm notice
npm notice New major version of npm available! 10.9.2 -> 11.0.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.0.0
npm notice To update run: npm install -g npm@11.0.0
npm notice
開発サーバー起動
cd firststep
npm run dev -- -o
動作確認
ブラウザで、 http://localhost:3000
へアクセスする。
ウェルカムページが見える。 OK.
Next プロジェクトのビルド
npm run build
.output/server/index.mjs
にビルド結果のエントリーポイントが出力される。
シングルバイナリ化
esbuild を使ってバンドル・ミニファイ
npx esbuild .output/server/index.mjs --bundle --minify --platform=node --target=node14.17.0 --outdir=dist
Node のバージョンは、ビルド時間短縮のため、 nexe が提供している最新のプレビルドバイナリのバージョンで動くものを指定
これで、 ./dist/index.js
にバンドル・ミニファイされたソースコードが出力される。
nexe を使ってシングルバイナリ化
npx nexe -i dist/index.js -o firststep --target windows-x64-14.15.3
windows-x64-14.15.3
が「nexe
が提供している最新のプレビルドバイナリのバージョン」。
これで、 ./firststep.exe
に実行バイナリが出力される。
動作確認
firststep.exe
を Windows
へ持っていき、ダブルクリック。
http://localhost:3000
へアクセス。OK.
もっと複雑なアプリケーションの場合は分からないが、 Get Started レベルのアプリならこれで OK なようだ。
最新の Node.js でビルドする
-b
オプションを追加すると、指定した Node.js
のソースをダウンロードし、 Node.js のビルドから開始する。
そのため、より新しい Node.js を使用したい場合には -b
オプションを追加したうえで、 Node
のバージョンに所望のバージョンを指定する。
npx esbuild .output/server/index.mjs --bundle --minify --platform=node --target=node22.13.1 --outdir=dist
npx nexe -i dist/index.js -o firststep -b --target windows-x64-22.13.1
Node.js のビルドが走るので、最悪数時間のビルド時間がかかる。
ただ、ビルド後の Node.js は ~/.nexe
にキャッシュされるので、 2 回目以降のビルドは早くなる。
以上。