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

如何预渲染Vite创建的React应用?react-snap生产构建失败

解决Vite+React项目react-snap预渲染构建失败问题

1. 调整Vite配置(vite.config.js)

react-snap默认读取build目录(与create-react-app保持一致),需修改Vite构建输出配置,同时避免代码分割导致预渲染异常:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'build', // 指定输出目录为react-snap默认读取的build
    emptyOutDir: true,
    rollupOptions: {
      output: {
        manualChunks: undefined, // 禁用自动代码分割,防止预渲染时chunk加载问题
      },
    },
  },
  base: './', // 部署到根路径用'/', 子路径替换为对应路径(如'/my-app/')
});

2. 完善react-snap配置(package.json)

在package.json中添加构建脚本和react-snap专属配置,明确预渲染路由、跳过第三方请求避免构建卡住:

{
  "scripts": {
    "build": "vite build && react-snap",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build" // 若用其他部署工具,替换为对应命令
  },
  "reactSnap": {
    "source": "build",
    "publicPath": "./",
    "skipThirdPartyRequests": true, // 跳过预渲染时的第三方接口请求
    "include": ["/", "/about", "/contact"], // 列出所有需要预渲染的路由
    "exclude": ["/admin"] // 排除不需要预渲染的路由(如后台页)
  }
}

3. 优化入口文件代码

React 18推荐使用hydrateRoot专门处理预渲染后的 hydration 逻辑,替代原createRoot().hydrate写法,同时确保路由、Suspense配置兼容静态预渲染:

import React from 'react';
import { hydrateRoot, createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Suspense } from 'react';
import { Provider } from 'react-redux';
import Loader from './Loader';
import store from './store';
import App from './App';

const Main = (
  <React.StrictMode>
    <BrowserRouter>
      <Suspense fallback={<Loader />}>
        <Provider store={store}>
          <App />
        </Provider>
      </Suspense>
    </BrowserRouter>
  </React.StrictMode>
);

const rootElement = document.getElementById('root');

if (rootElement.hasChildNodes()) {
  // 预渲染后的节点用hydrateRoot激活交互
  hydrateRoot(rootElement, Main);
} else {
  createRoot(rootElement).render(Main);
}

4. 调整GitHub Actions部署脚本

确保CI环境中正确安装依赖、执行完整构建+预渲染流程:

name: Deploy to GitHub Pages

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build and pre-render
        run: npm run build

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v4
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./build

内容的提问来源于stack exchange,提问作者Md. Zayed Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:42:41