はじめに
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.ts
のplugins
にcloseBundle
フックを使ってファイル名を変更する処理を追加するだけで、簡単に実現できます。
最後に
GoQSystemでは一緒に働いてくれる仲間を募集中です!
ご興味がある方は以下リンクよりご確認ください。