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

如何在WordPress自定义主题中集成Vite解决localhost:5173 404问题

解决Vite+WordPress开发中localhost:5173 404错误的方案

1. 配置Vite代理转发请求到WordPress本地站点

Vite的开发服务器默认独立运行,而你的WordPress内容托管在http://mysite.localhost,需要让Vite将请求代理到该站点才能加载WordPress页面内容。修改vite.config.js添加代理配置:

import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    proxy: {
      '/': {
        target: 'http://mysite.localhost',
        changeOrigin: true,
        secure: false, // 本地站点用HTTP,设为false
      },
    },
  },
});

配置后,访问http://localhost:5173时,Vite会把所有请求转发到你的WordPress本地站点,避免404。

2. 区分开发/生产环境的资源入队逻辑

WordPress的资源入队函数需要根据环境加载不同资源:开发环境加载Vite开发服务器的资源,生产环境加载打包后的静态文件。修改主题的functions.php:

function enqueue_theme_assets() {
  // 先在wp-config.php中定义WP_ENV常量
  if (defined('WP_ENV') && WP_ENV === 'development') {
    // 开发环境加载Vite HMR资源
    wp_enqueue_script('theme-main-js', 'http://localhost:5173/src/main.js', array(), null, true);
    wp_enqueue_style('theme-main-css', 'http://localhost:5173/src/style.css');
  } else {
    // 生产环境加载打包后的资源(需配合Vite的manifest)
    $manifest_path = get_template_directory() . '/dist/manifest.json';
    if (file_exists($manifest_path)) {
      $assets = json_decode(file_get_contents($manifest_path), true);
      wp_enqueue_script('theme-main-js', get_template_directory_uri() . '/dist/' . $assets['src/main.js']['file'], array(), $assets['src/main.js']['hash'], true);
      wp_enqueue_style('theme-main-css', get_template_directory_uri() . '/dist/' . $assets['src/style.css']['file'], array(), $assets['src/style.css']['hash']);
    }
  }
}
add_action('wp_enqueue_scripts', 'enqueue_theme_assets');

同时在wp-config.php中添加环境定义:

define('WP_ENV', 'development'); // 生产环境改为'production'

3. 确认XAMPP服务状态

确保XAMPP的Apache服务处于运行状态,且http://mysite.localhost能正常访问——Vite的代理依赖这个站点的可用性,如果WordPress站点本身无法访问,代理后自然会返回404。

4. 检查Vite入口文件配置

确认vite.config.js中指定的入口文件路径正确,比如如果你的源码在src目录,要保证Vite能找到对应的main.js或style.css,避免因入口不存在导致的404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:18:17