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

在WordPress中使用Vite/Laravel Vite Plugin时热重载失效并报错

解决WordPress主题Vite Dev模式下Cannot use import statement outside a module报错

核心原因

  • WordPress模板直接加载了未经过Vite处理的原生app.js文件,而非Vite Dev Server提供的ES模块入口
  • 脚本加载标签未添加type="module"属性,浏览器无法识别ES模块语法
  • Vite配置未适配WordPress的本地开发环境,导致模块加载路径或跨域问题

分步解决办法

1. 修正WordPress脚本加载逻辑

在主题的functions.php中,区分开发/生产环境加载对应脚本,开发环境必须加载Vite客户端并声明模块类型:

function enqueue_theme_assets() {
    $is_dev = defined('WP_ENV') && WP_ENV === 'development';
    
    if ($is_dev) {
        // 加载Vite Dev Server客户端脚本
        wp_enqueue_script('vite-client', 'http://localhost:5173/@vite/client', [], null, true);
        // 加载Vite入口模块
        wp_enqueue_script('theme-app', 'http://localhost:5173/resources/js/app.js', [], null, true);
        
        // 为入口脚本添加type="module"属性
        add_filter('script_loader_tag', function($tag, $handle) {
            if ($handle === 'theme-app') {
                return str_replace('<script ', '<script type="module" ', $tag);
            }
            return $tag;
        }, 10, 2);
    } else {
        // 生产环境加载打包后的资源(依赖Vite生成的manifest.json)
        $manifest = json_decode(file_get_contents(get_template_directory() . '/dist/manifest.json'), true);
        wp_enqueue_script(
            'theme-app',
            get_template_directory_uri() . '/dist/' . $manifest['resources/js/app.js']['file'],
            [],
            $manifest['resources/js/app.js']['hash'],
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'enqueue_theme_assets');

2. 调整Vite配置文件(vite.config.mjs)

确保配置适配WordPress本地环境,设置正确的入口、输出和跨域规则:

import { defineConfig } from 'vite';
import wordpressPlugin from 'vite-plugin-wordpress';

export default defineConfig({
    plugins: [wordpressPlugin()],
    root: './',
    build: {
        outDir: './dist',
        manifest: true,
        rollupOptions: {
            input: {
                app: './resources/js/app.js',
                // 如有CSS入口也可添加,比如:style: './resources/css/style.css'
            },
        },
    },
    server: {
        port: 5173,
        host: '0.0.0.0',
        origin: 'http://localhost:5173',
        allowedHosts: ['localhost', 'your-wp-local-domain.test'], // 替换为你的WP本地域名
        cors: true,
    },
});

3. 确认package.json配置

添加"type": "module"确保Node.js识别ES模块,同时检查脚本命令:

{
    "name": "your-wp-theme",
    "type": "module",
    "scripts": {
        "dev": "vite",
        "build": "vite build"
    },
    "devDependencies": {
        "vite": "^5.0.0",
        "vite-plugin-wordpress": "^1.0.0"
    }
}

4. 验证app.js的模块语法

确保app.js使用标准ES模块语法:

// 示例app.js
import './components/navigation.js';
import { initializeGallery } from './utils/gallery.js';

document.addEventListener('DOMContentLoaded', () => {
    initializeGallery();
});

验证操作

  1. 重启Vite Dev Server:执行npm run dev
  2. 清除WordPress缓存和浏览器缓存
  3. 刷新WP页面,检查控制台是否消除报错

内容的提问来源于stack exchange,提问作者Andy Holmes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 00:42:38