0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTMLで参照しているTypeScriptを直接実行させる

Posted at

こちらの記事で紹介して頂いた、TypeScriptを直接実行させる方法を、tsファイルが外部ファイルでも直接実行できるようにバージョンアップさせていただきました。

解説は元の記事で詳しく説明されているので、そちらを参照ください

<script async type="module">
  import { transpile, ScriptTarget } from "https://esm.sh/typescript@5.8.3?target=esnext";
  import { minify } from "https://esm.sh/terser@5.39.0?target=esnext";

  // esnext-polyfill
  Uint8Array.prototype.toBase64 ??= function () {
    return btoa(Array.from(this, (v) => String.fromCharCode(v)).join(""));
  }

  // すべてのスクリプトを処理
  runTypeScripts();

  async function compileTypeScript(tsCode) {
    const js = transpile(tsCode, {
      target: ScriptTarget.ESNext,
    });

    // コードの短縮化
    const { code } = await minify(js, {
      module: true,
      // consoleログの個所をすべて削除するかどうか
      compress: {
        drop_console: false // true: 削除, false: 削除しない
      }
    });

    // コードをimportして実行
    await import(`data:text/javascript;base64,${new TextEncoder().encode(code).toBase64()}`);
  }

  async function runTypeScripts() {
    for (const script of document.getElementsByTagName("script")) {
      // TypeScriptスクリプト以外はスキップ
      if (script.type !== "text/typescript") continue;

      // 即時関数でTypeScriptコードを取得
      const tsCode = await (async () => {
        if (script.textContent) {
          // インラインTypeScriptの処理
          return script.textContent;
        }
        if (script.src) {
          // 外部ファイルの処理
          const response = await fetch(script.src);
          if (response.ok) {
            return await response.text();
          }
        }
      })();

      if (tsCode) {
        await compileTypeScript(tsCode);
      }
    }
  }
</script>
<script src="script.ts" type="text/typescript"></script>

元の記事のように直接typescriptを<script>タグ内に記述する方法でも
外部ファイル(例では"script.ts")を読み込ませる方法でもどちらでも可となっています

注意:イベント発生タイミングが通常のケースと違うため気を付けてください
onLoadイベントとか

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?