You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress/WordPlate中实现Vite.js的HMR自动更新

解决WordPress/WordPlate中Vite HMR(热模块替换)不生效的问题

核心问题分析

当前无法触发样式HMR的主要原因:

  1. 你在index.js中导入的是编译后的index.css,而非源文件index.scss,导致Vite无法监听源文件的变化并触发热更新。
  2. functions.php中使用了重复的脚本handle,导致@vite/client被覆盖,丢失HMR通信能力。
  3. Vite服务器配置缺少必要的跨域和访问设置,影响HMR连接。

分步解决方案

1. 修改index.js,直接导入SCSS源文件

将原来导入编译后CSS的代码改为导入SCSS源文件,让Vite直接处理样式编译与热更新:

// 替换原来的 import "../css/index.css";
import "../css/index.scss";

2. 完善Vite配置(vite.config.js)

添加server配置项,确保Vite服务器可被外部访问,同时支持跨域:

import { defineConfig } from "vite";
require("dotenv").config();

export default defineConfig(() => ({
  publicDir: "resources/static",
  // 新增server配置
  server: {
    host: "0.0.0.0", // 允许外部访问
    port: 5173,
    origin: "http://localhost:5173", // 与Vite运行地址保持一致
    cors: true, // 允许跨域请求
  },
  build: {
    assetsDir: "",
    emptyOutDir: true,
    manifest: true,
    outDir: `public/themes/${process.env.WP_DEFAULT_THEME}/assets`,
    rollupOptions: {
      input: `public/themes/${process.env.WP_DEFAULT_THEME}/resources/js/index.js`,
    },
  },
  plugins: [
    {
      name: "php",
      handleHotUpdate({ file, server }) {
        if (file.endsWith(".php")) {
          server.ws.send({ type: "full-reload", path: "*" });
        }
      },
    },
  ],
}));

3. 修复functions.php中的脚本加载问题

  • 避免重复的脚本handle,拆分@vite/client和主脚本
  • 优化Vite运行状态的判断逻辑
  • 移除不必要的defer属性(模块脚本默认延迟加载)
<?php
function my_theme_enqueue_styles()
{
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
}

add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');

// Register scripts and styles.
add_action('wp_enqueue_scripts', function () {
    $manifestPath = get_theme_file_path('assets/manifest.json');
    $viteRunning = false;

    // 更可靠的Vite运行状态检测
    if (wp_get_environment_type() === 'local') {
        $response = wp_remote_get('http://localhost:5173');
        $viteRunning = !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200;
    }

    if ($viteRunning) {
        // 使用不同的handle,避免脚本覆盖
        wp_enqueue_script('vite-client', 'http://localhost:5173/@vite/client', [], null, true);
        wp_enqueue_script('vite-main', 'http://localhost:5173/resources/js/index.js', [], null, true);
    } elseif (file_exists($manifestPath)) {
        $manifest = json_decode(file_get_contents($manifestPath), true);
        wp_enqueue_script(
            'vite-main',
            get_theme_file_uri('assets/' . $manifest['resources/js/index.js']['file']),
            [],
            null,
            true
        );
        wp_enqueue_style(
            'vite-style',
            get_theme_file_uri('assets/' . $manifest['resources/css/index.css']['file']),
            [],
            null
        );
    }
});

// Load scripts as modules.
add_filter('script_loader_tag', function (string $tag, string $handle, string $src) {
    if (in_array($handle, ['vite-client', 'vite-main'])) {
        return '<script type="module" src="' . esc_url($src) . '"></script>';
    }

    return $tag;
}, 10, 3);

4. 安装SCSS预处理器依赖

如果尚未安装,执行以下命令安装Vite处理SCSS所需的依赖:

npm install sass --save-dev

验证步骤

  1. 重启Vite开发服务器
  2. 修改index.scss内容,观察浏览器是否自动更新样式
  3. 修改PHP文件,确认页面会自动全量刷新

内容的提问来源于stack exchange,提问作者Etoundi Oyono Georges Lévy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:05:27