Vite+React+TypeScript应用部署到Apache服务器问题求助
解决Vite+React+TypeScript部署到XAMPP Apache的空白页问题
你遇到的空白页问题,核心是资源路径不匹配和路由基准未配置,以下是具体解决步骤:
1. 配置Vite的基础路径(base)
因为你的应用部署在XAMPP的/temp子目录下,Vite默认的资源基准路径是根目录/,导致浏览器会从http://localhost/加载资源,而不是http://localhost/temp/,这会引发资源404,页面无法渲染。
操作步骤:
- 在项目根目录找到或创建
vite.config.ts文件,添加base配置:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], base: '/temp/' // 对应XAMPP里的子目录名称 })
- 重新执行
npx vite build,将新生成的dist文件夹内容覆盖到C:\XAMPP\htdocs\temp
2. 适配React Router的路由基准
React Router默认以根路径/作为路由基准,部署到子目录后需要同步修改,否则路由逻辑会出错。
操作步骤:
- 找到项目入口文件(通常是
src/main.tsx),在<BrowserRouter>标签上添加basename="/temp"属性:
import React from 'react' import ReactDOM from 'react-dom/client' import { BrowserRouter } from 'react-router-dom' import App from './App.tsx' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <BrowserRouter basename="/temp"> <App /> </BrowserRouter> </React.StrictMode>, )
- 再次执行
npx vite build并更新XAMPP目录下的文件
3. 验证资源加载状态
打开浏览器开发者工具(F12),切换到「Network」标签,刷新页面:
- 检查JS、CSS、图片等资源的请求路径是否为
http://localhost/temp/xxx格式 - 如果资源返回404,说明base配置仍有问题,重新核对配置项
4. 配置Apache重写规则(解决路由刷新404问题,可选)
如果部署后直接访问子路由(比如http://localhost/temp/store)出现404,需要配置Apache的重写规则,让所有路由请求都指向index.html:
- 在
C:\XAMPP\htdocs\temp目录下创建.htaccess文件,写入以下内容:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /temp/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /temp/index.html [L] </IfModule>
- 开启Apache的mod_rewrite模块:打开XAMPP控制面板,点击Apache的「Config」→「httpd.conf」,找到
#LoadModule rewrite_module modules/mod_rewrite.so,删除前面的#,保存后重启Apache
内容的提问来源于stack exchange,提问作者Mich
相关产品推荐
相关产品推荐

