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

Vite.js SSR结合react-router-dom无法正常运行的问题求助

解决Vite SSR集成react-router-dom的运行异常问题

问题原因

  1. 服务器端渲染环境中,BrowserRouter依赖浏览器的window对象,直接使用会导致服务器端报错。
  2. 将react-router-dom加入ssr.external配置,会让Vite跳过对该包的转译处理,服务器端无法正确解析其ES模块语法。

解决方案步骤

1. 调整Vite配置

移除ssr.external中的react-router-dom,修改后的vite.config.ts:

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

export default defineConfig({
    plugins: [react()],
    resolve: {
        alias: {
            "@App": path.resolve(process.cwd(), "src"),
            "@Components": path.resolve(process.cwd(), "src/Components"),
            "@Pages": path.resolve(process.cwd(), "src/pages"),
            "@Styles": path.resolve(process.cwd(), "src/Styles"),
            "@Public": path.resolve(process.cwd(), "public")
        },
    },
})

2. 拆分客户端与服务器端路由逻辑

通用路由组件(src/App.tsx)

import { Routes, Route } from 'react-router-dom';

export function App() {
  return (
    <Routes>
      <Route path="/" element={<div>HI</div>} />
      {/* 可添加更多路由规则 */}
    </Routes>
  );
}

客户端入口(src/entry-client.tsx)

使用浏览器端专用的BrowserRouter包裹应用:

import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { App } from './App';

createRoot(document.getElementById('root')!).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

服务器端入口(src/entry-server.tsx)

使用服务器端专用的StaticRouter(来自react-router-dom/server)处理请求URL:

import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import { App } from './App';

export async function render(url: string, manifest: Record<string, string[]>) {
  const html = renderToString(
    <StaticRouter location={url}>
      <App />
    </StaticRouter>
  );

  return `<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
    ${manifest['src/main.tsx'] ? manifest['src/main.tsx'].map(file => `<link rel="stylesheet" href="/${file}">`).join('') : ''}
  </head>
  <body>
    <div id="root">${html}</div>
    ${manifest['src/main.tsx'] ? manifest['src/main.tsx'].map(file => `<script type="module" src="/${file}"></script>`).join('') : ''}
  </body>
</html>`;
}

3. 确保依赖安装

如果尚未安装react-router-dom,执行以下命令:

yarn add react-router-dom

验证运行

重新执行yarn dev,即可正常启动集成react-router-dom的Vite SSR应用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:57:37