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

Vite+React多页面应用访问/tags/路径默认跳转至首页问题

React多页面应用/tags路由加载异常修复方案

问题描述

计划实现两个主页面:localhost:3001/(首页)和localhost:3001/tags/(标签页),但访问localhost:3001/tags/时显示的是首页内容,页面标题本该是“Tags”却显示“Homepage”,标签页未正确加载。

当前文件结构

.env
index.html
package.json
vite.config.ts
etc.
src/
  | App.tsx
  | main.tsx
  | tags/
    | index.html
    | tags.tsx

当前配置情况

  • 根目录index.html:script标签为src="/src/main.tsx",标题为“Homepage”
  • src/tags/index.html:标题设为<title>Tags</title>,script标签为src="./tags.tsx"
  • tags.tsx:仅通过createRoot()渲染简单的“Hello world”内容
  • vite.config.ts:已在build.rollupOptions中配置多页面入口,但开发服务器未做对应路由处理

修复步骤

1. 修正标签页index.html的script路径

src/tags/index.html里的相对路径会导致开发服务器找不到文件,改成绝对路径:

<!-- 原代码 -->
<script type="module" src="./tags.tsx"></script>

<!-- 修改后 -->
<script type="module" src="/src/tags/tags.tsx"></script>

同时确保该文件内存在根元素容器,和首页一致:

<div id="root"></div>

2. 配置Vite开发服务器的路由重写

Vite开发模式默认只会指向根目录的index.html,需要添加中间件让/tags路由指向标签页的html文件。修改vite.config.ts:

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

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3001,
    async configureServer(server) {
      server.middlewares.use((req, res, next) => {
        // 拦截/tags开头的请求,返回标签页的html
        if (req.url?.startsWith('/tags')) {
          const tagsHtmlPath = path.resolve(__dirname, 'src/tags/index.html')
          return server.transformIndexHtml(tagsHtmlPath, '', req.originalUrl)
        }
        next()
      })
    }
  },
  build: {
    outDir: 'dist',
    emptyOutDir: true,
    rollupOptions: {
      input: {
        main: 'index.html',
        tags: 'src/tags/index.html'
      }
    }
  }
})

3. 确认tags.tsx的渲染逻辑正确

确保tags.tsx里的根元素选择器和标签页index.html的容器匹配:

import { createRoot } from 'react-dom/client'

// 这里的root要和src/tags/index.html里的容器id一致
createRoot(document.getElementById('root')!).render(
  <h1>Hello Tags Page</h1>
)

4. 重启开发服务器

修改Vite配置后必须重启服务,才能让新配置生效。


验证

重启后访问localhost:3001/tags/,应该显示“Hello Tags Page”,页面标题为“Tags”,说明标签页已正确加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:47:26