🦔

続・ビルドしない Angular アプリ開発

2023/12/23に公開

ビルド不要の Angular アプリケーションを Babel を用いて書くことができました。
Babel による TypeScript のトランスパイルをブラウザ上で実行し、より自然な書き方で Angular アプリケーションのコードを書くことができます。

前回の記事

デモ

コード

今回のコードは Bebel でトランスパイルすることによりデコレータ構文が使えるようになりました。併せて TypeScript も使うようにしました。

解説

@babel/standalone

<script type="module">
  import {
    availablePlugins,
    availablePresets,
    registerPreset,
  } from "https://esm.sh/@babel/standalone@7.23.6";

  registerPreset("angular", {
    presets: [[availablePresets["typescript"]]],
    plugins: [
      [availablePlugins["proposal-decorators"], { version: "legacy" }],
      [availablePlugins["transform-class-properties"]],
    ],
  });
</script>
<!-- `data-plugins=""` attribute is required for @babel/standalone@7.23.6 -->
<script type="text/babel" data-presets="angular" data-plugins="" data-type="module" src="./main.ts"></script>

ブラウザ環境で Babel のトランスパイル機能を使えるようにするツールです。以下の3つのトランスパイルを使用しています。

なお、 @babel/standalone@7.23.6 時点では data-plugins="" のような指定をしないとデコレータのトランスパイルができないようです。 Maintainer からのコメント

最近登場した類似の代替ツールとして esm.sh/run がありますが、これだとデコレータの変換ができませんでした。トランスパイルのためにコードを外部に送信するため社用のツールを開発するのには不向きです。

@angular/compilerzone.js

(前回の記事より再掲)

main.js
import "@angular/compiler";
import "zone.js";

無いと動作しないようです。

`@angular/compiler` が無い場合のエラー
Uncaught Error: The injectable '_PlatformLocation' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.

The injectable is part of a library that has been partially compiled.
However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.

Ideally, the library is processed using the Angular Linker to become fully AOT compiled.
Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',
or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.
`zone.js` が無い場合のエラー
Uncaught Error: NG0908: In this configuration Angular requires Zone.js

Discussion