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?

Viteでビルド時にHTMLをPHPファイルで出力する方法

Last updated at Posted at 2025-07-31

はじめに

ViteでビルドしたHTMLファイルをPHPファイルとして出力する方法を備忘録として残します。 今回はReact x TypeScriptの例で紹介しますが、VueやSvelteなど他のフレームワークでも同様に実装できます。

実行環境

以下のバージョンで動作を確認しています。

Node.js: v22.17.0
Vite: ^7.0.4

環境構築

viteプロジェクトを作成した後に、Node.jsの型定義をインストールします。

npm install -D @types/node

実装方法

vite.config.tsファイルのdefineConfig関数のpluginsに、ビルド完了後にHTMLファイルの拡張子を変更する処理を追加します。

closeBundleは、Viteのプラグインフックの一つで、バンドル処理が完了した直後に実行されます。このフックを利用して、distディレクトリに生成されたindex.htmlファイルをindex.phpにリネームします。

import fs from "node:fs";
import path from "node:path";

// HTMLファイルをPHPファイルへ変換
function renameHtmlToPhp() {
  const distPath = path.resolve(__dirname, "dist");
  const htmlFilePath = path.join(distPath, "index.html");
  const phpFilePath = path.join(distPath, "index.php");

  try {
    // index.htmlをindex.phpにリネーム
    fs.renameSync(htmlFilePath, phpFilePath);
    console.log(`✅ ${htmlFilePath}${phpFilePath} に変換しました。`);
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(`❌ ファイルの変換中にエラーが発生しました: ${errorMessage}`);
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(),
    {
      name: "rename",
      closeBundle() {
        renameHtmlToPhp();
      },
    },
  ],
});

また、自動的に再ビルドを行うコマンドもご紹介します。
package.jsonファイルのscriptsセクションに下記を追加します。

"scripts": {
  "build:watch": "tsc -b && vite build --watch"
}

TypeScriptを使用していない場合や型チェックが不要な場合は、下記のようにしてください。

"scripts": {
  "build:watch": "vite build --watch"
}

まとめ

この記事では、ViteでビルドしたHTMLファイルをPHPファイルとして出力する方法を紹介しました。vite.config.tspluginscloseBundleフックを使ってファイル名を変更する処理を追加するだけで、簡単に実現できます。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

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?