WordPressとVue(Vite)を組み合わせて開発する際、「ちょっとした修正でも毎回ビルドが必要…」と感じたことはありませんか?この記事では、Viteのホットリロード機能を活かして、WordPressテーマ内でリアルタイムにVueを反映させる方法をご紹介します。
開発環境の前提
- WordPress ローカル環境(例: http://example-site.local)
- Vue 3(Vite + TypeScript + vue-router + pinia)
- Element Plus 使用
- Vueビルドファイルの配置:
/wp-content/themes/my-theme/vue-app/
編集が必要なファイル一覧
ファイル名 | 役割 |
---|---|
vite.config.ts | ViteのCORS設定を追加 |
page-spa-app.php | WordPressのテンプレートファイル。Vueを読み込む |
wp-config.php | 開発モードを定義(WP_ENV) |
Viteの設定(CORS許可)
vite.config.ts に以下を追加して、WordPressからのアクセスを許可します。
server: {
origin: 'http://localhost:5173',
cors: {
origin: ['http://example-site.local'],
methods: ['GET', 'POST'],
credentials: true,
},
},
WordPressテンプレートでVueを読み込む
page-spa-app.php に以下のように記述します。
<?php
/*
Template Name: SPAアプリページ
Template Post Type: page
*/
get_header('spa');
?>
<div id="app"></div>
<?php get_footer('spa'); ?>
<?php if (defined('WP_ENV') && WP_ENV === 'development'): ?>
<!-- Vite開発サーバーから読み込み -->
<script type="module" src="http://localhost:5173/src/main.ts"></script>
<?php else: ?>
<!-- 本番用ビルドファイルを読み込み -->
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/vue-app/dist/assets/index.css">
<script type="module" src="<?php echo get_template_directory_uri(); ?>/vue-app/dist/assets/index.js"></script>
<?php endif; ?>
functions.php の編集は不要で、wp_enqueue_script()
も使用しません。
WordPressの開発モード定義
wp-config.php に以下を追記します。
define('WP_ENV', 'development'); // 本番時は 'production'
開発の流れ
- ターミナルで
npm run dev
を実行し、Viteを起動 - WordPressの
/spa-app
ページを開く - Vueファイルを保存 → 自動でブラウザに反映!(ホットリロード)
さいごにまとめ
- ビルドの手間: ✅ 不要!
- Vue修正後の反映: ✅ 保存するだけ!
- WordPress連携: ✅ そのままVueを使える!
- functions.php: ❌ 編集不要!
VueとWordPressの開発をもっと快適にしたい方は、ぜひこの方法を取り入れてみてください。シンプルですが、開発効率が大幅に向上します!