ViteでWordPressの編集する

インストール

npm init -y

プロジェクトの基本設定ファイル(package.json)を作成する。

npm install -D vite

Vite本体をプロジェクトにインストールする。-Dpackage.jsondevDependencies に追加を意味する。これは、Viteが開発中やビルド時にのみ必要なツールであり、公開用の本番環境には含まれない。

npm install -D sass

Sass(Dart Sass)も開発用依存関係としてインストールする。

npm install -D vite-plugin-live-reload

PHPの開発環境でViteを使用し、PHPファイル(.php)の変更を検知してブラウザを自動リロードさせるプラグイン vite-plugin-live-reload をインストールする。
Viteは通常、JSやCSSの変更を高速に反映(HMR)するが、サーバーサイド言語であるPHPの変更は標準では監視しないのでこのプラグインを使うことで、PHPファイルが保存された際、Vite経由でリロードさせる。

package.jsonを編集

//package.json

"scripts": {
  "dev": "vite",
  "build": "vite build",
},

package.json を開き、dev、build、を追記する。

  • npm run dev:
    開発サーバーを起動する。PHPのリロードやJSのHMR(高速反映)が有効なモード。
  • npm run build:
    本番公開用のファイルを書き出す。vite.config.js で設定した dist フォルダに、最適化されたJSやCSS、そして manifest.json が生成される。

WordPressのfunction.phpを編集

//functions.php

/**
 * Viteで「開発時」と「公開時」で読み込むファイルの場所を切り替える
 */
function my_theme_enqueue_scripts() {
    // 開発環境かどうかを判定
    $is_dev = true; // まずは確実に動かすために強制的にtrueにする

    if ($is_dev) {
        // Vite サーバーが起動している前提で読み込み
        wp_enqueue_script('vite-client', 'http://localhost:5173/@vite/client', [], null, true);
        wp_enqueue_script('my-theme-js', 'http://localhost:5173/src/main.js', ['vite-client'], null, true);
    } else {
        // 本番環境(build後)の設定
        $manifest_path = get_template_directory() . '/dist/.vite/manifest.json';
        
        // ファイルが存在するか確認してから読み込む(500エラー対策)
        if (file_exists($manifest_path)) {
            $manifest = json_decode(file_get_contents($manifest_path), true);
            if (isset($manifest['src/main.js'])) {
                wp_enqueue_script('my-theme-js', get_template_directory_uri() . '/dist/' . $manifest['src/main.js']['file'], [], null, true);
            }
        }
    }
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');



/**
 * Vite関連のスクリプトタグに type="module" を付与する
 */
add_filter('script_loader_tag', function($tag, $handle, $src) {
    // Viteに関係するハンドル名(wp_enqueue_scriptで指定したもの)を配列に指定
    $targets = ['vite-client', 'my-theme-js'];

    if (!in_array($handle, $targets)) {
        return $tag;
    }

    // type="module" を追加したタグを作成
    $tag = '<script type="module" src="' . esc_url($src) . '"></script>';
    return $tag;
}, 10, 3);

WordPressのfunctions.phpでViteが「開発時」と「公開時」で読み込むファイルの場所を切り替えるための設定。

Viteのvite.config.jsを編集

// vite.config.js

import { defineConfig } from 'vite';
import liveReload from 'vite-plugin-live-reload'; // 追加:liveReloadプラグインの読み込み
import { resolve } from 'path'; // 追加:resolve関数の読み込み
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// ESモジュールで __dirname を使用するための設定
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export default defineConfig({
  plugins: [
    // テーマ内のすべてのPHPファイルを監視対象にする
    liveReload(__dirname + '/**/*.php'),
  ],
  server: {
    port: 5173,
    strictPort: true,
    proxy: {
      // /wordpress/ というパスを含めてプロキシを設定
      '^(?!/(src|node_modules|@vite|@id|@fs|@devtools)).*': {
        target: 'http://localhost', // 実際のWordPressが動いているURL
        changeOrigin: true,
      },
    },
  },
  build: {
    outDir: 'dist',
    manifest: true,
    rollupOptions: {
      input: resolve(__dirname, 'src/main.js'),
    },
  },
});

vite.config.jsの設定

ブラウザで確認

/localhost/wordpressのディレクトリ/
で確認する。