1
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?

More than 1 year has passed since last update.

動的に取得したHtmlファイルを起点にViteでHMRな開発環境を構築する(メモ)

Last updated at Posted at 2023-03-15

HTMLを生成するWebアプリからHTMLファイルに含まれるログインユーザーのパラメータを取得したい、という要件があるプラグイン的なアプリを作る機会があったのでメモ(備忘録)

理由と状況

image.png

  • 既存アプリはログイン認証の結果がHTMLに含まれる
  • 既存アプリのステージングAPIを叩きたい
  • 最終的にはjsファイルを生成して既存アプリにプラグインのような形で配信する
  • 開発環境でhmrな楽しいコーディングがしたい

何をすれば解決するか

既存アプリのWebサーバーから取得したHTMLファイルに・・・・

<script type="module" src="/main.ts"></script>

Viteで管理しているsrcフォルダのスクリプトの起点ファイルを読み込むタグがあれば良い。以上。

これだけだと面白みが無いので一応サンプルコードを。

サンプル用構成

image.png

express側

import dayjs from 'dayjs';
import express from 'express';

const app = express();
app.get(/^\/$/, (req, res) => {
  res.writeHead(302, { Location: '/index.html' });
  res.end();
});
const server = app.listen(8000, function () {
  console.log('Express Run', `Port = ${server.address().port} `);
});

app.get('/index.html', function (req, res, next) {
  const ts = dayjs().format('YYYY-MM-DD HH:mm:ss.SSS');
  const html = `
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/vite.svg" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title></title>
    </head>
    <body>
      <div> expressで出力${dayjs().format('YYYY-MM-DD HH:mm:ss.SSS')}</div>
        <div id="app"></div>
        <!-- ↓ これが重要なやつ ↓ -->
        <script type="module" src="/main.ts"></script>
    </body>
</html>
`;
  res.end(html);
});

Vite側

なにも設定しないとvite.config.tsのrootプロパティで指定されたhtmlファイルを読みに行ってしまうので

vite.config.ts
export default defineConfig(({ command, mode }) => {
    return {
            root: 'src',
            base: '/',
            //省略
        },
        server: {
            port: 8888,
            //省略
            proxy: {
                '^/$': {
                  target: 'http://localhost:8000',
                  changeOrigin: true,
                },
                '/index.html': {
                  target: 'http://localhost:8000',
                  changeOrigin: true,
                },
            },
        },
    };
});

proxyで無理やりexpressに向いてもらいます。

結果
動的サーバーからHTMLファイルを取得しながら
Viteの高速ビルドでhmrな幸せ開発環境でコーディングが可能となります。

image.png

シンプルなのですが・・・

GitHubにサンプル上げてます

1
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
1
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?