DEV Community

Suguru Inatomi
Suguru Inatomi

Posted on

6

AngularでWeb Bundlesを試す

Angularアドベントカレンダー #2の24日目代打記事です。

Web Bundlesとは、現在標準化が検討されている新しいWebの仕様です。Webページとそれに紐づくサブリソースをひとつのバンドルとしてパッケージ化することができます。

この記事ではWeb Bundlesを手元のAngularアプリケーションで試してみたい人向けの手順を紹介します。

CLI Builderのインストール

lacolaco/ngx-web-bundlesというパッケージで、Angular CLI向けのBuilderを作っています。
次のコマンドを実行するだけで、Web Bundleをビルドする準備が整います。

$ ng add @lacolaco/ngx-web-bundle
Enter fullscreen mode Exit fullscreen mode

インストールできたら、 任意のプロジェクトでgen-bundleコマンドを実行します。

$ ng run <project name>:gen-bundle
Enter fullscreen mode Exit fullscreen mode

ビルドが終わるとindex.htmlが出力されるdistディレクトリと同じ階層に out.wbn というファイルが生成されているはずです。このファイルをGoogle ChromeのCanary版で Web Bundlesを有効にしてから開くと、バンドルを展開できるはずです。

How it works

ngx-web-bundleがやっているのは2つのことです。

  1. ng add されたときに angular.json を更新し、 gen-bundleコマンドを定義する
  2. gen-bundleコマンドが実行されたときに処理する

ng-add時の動き

ng-add時に動くのは次のngAdd関数です。

https://github.com/lacolaco/ngx-web-bundles/blob/master/schematics/ng-add/index.ts#L15

やっていることは次の2つです。

  1. 対象とするプロジェクトを特定する
  2. プロジェクトの architectsgen-bundleを追加する

gen-bundle時の動き

gen-bundleコマンドで動くのは次のbuild関数です。

https://github.com/lacolaco/ngx-web-bundles/blob/master/index.ts#L51

やっていることは次の3つです。

  1. executeBrowserBuilder を使って、アプリケーションのビルドをおこなう(ng buildと同じ処理を実行する)
  2. ビルド後の生成物を wbn パッケージを使ってバンドル化する
  3. アプリケーションの生成物を同じ場所にバンドルを出力する

バンドル化の処理は次の関数に記述されています。特別に配慮が必要なのはindex.htmlだけで、それ以外はファイルごとに同じ処理をしています。

https://github.com/lacolaco/ngx-web-bundles/blob/master/index.ts#L24

ひとつひとつのやっていることはシンプルです。それらを組み合わせてルールに従って配置すれば簡単にAngular CLI経由で動かせるスクリプトを作成できます。

Takeaways

  • AngularでWeb Bundlesを試すなら @lacolaco/ngx-web-bundle をどうぞ
  • 自作のスクリプトをng addng runに対応させるのは意外に簡単です
    • デバッグはちょっと面倒です
  • Web Bundlesについては web.dev/web-bundles/ を参照してください

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay