如何在Vite开发服务器中配置适配Firebase规则的URL重写
配置Vite开发服务器实现Firebase托管式URL重写
问题背景
你的Firebase托管重写配置(firebase.json)如下:
"rewrites": [ { "source": "/spa/**", "destination": "/spa/index.html" }, { "source": "/exp/**", "destination": "/exp/index.html" }, { "source": "**", "destination": "/index.html" } ]
Vite构建配置(vite.config.js):
build: { rollupOptions: { input: { main: 'index.html', spa: '/spa/index.html', exp: '/exp/index.html', }, }, },
部署到Firebase后,访问site.com/exp/***等路径可正常重写,但本地Vite开发服务器无法实现相同效果,需要配置本地开发服务器的URL重写规则。
解决方案
可以通过两种方式在Vite开发服务器中实现对应重写:
方式一:手动编写中间件规则
直接在vite.config.js中添加自定义中间件,修改请求路径指向对应入口文件:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], build: { rollupOptions: { input: { main: 'index.html', spa: '/spa/index.html', exp: '/exp/index.html', }, }, }, server: { middlewareMode: 'ssr', async middleware(req, res, next) { // 匹配/spa路径及其子路径 if (req.url.startsWith('/spa/') || req.url === '/spa') { req.url = '/spa/index.html'; } // 匹配/exp路径及其子路径 else if (req.url.startsWith('/exp/') || req.url === '/exp') { req.url = '/exp/index.html'; } // 其他非静态资源路径,重写为根入口 else if (!req.url.match(/\.(js|css|png|jpg|svg|ico|json)$/)) { req.url = '/index.html'; } next(); }, }, });
方式二:使用connect-history-api-fallback中间件
借助专门的历史路由重写中间件,配置规则与Firebase保持一致:
- 先安装依赖:
npm install connect-history-api-fallback --save-dev
- 修改
vite.config.js:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import history from 'connect-history-api-fallback'; export default defineConfig({ plugins: [react()], build: { rollupOptions: { input: { main: 'index.html', spa: '/spa/index.html', exp: '/exp/index.html', }, }, }, server: { middlewareMode: 'ssr', async middleware(req, res, next) { const historyMiddleware = history({ rewrites: [ { from: /^\/spa\/.*$/, to: '/spa/index.html' }, { from: /^\/exp\/.*$/, to: '/exp/index.html' }, { from: /^\/.*$/, to: '/index.html' }, ], disableDotRule: true // 避免重写带点的静态资源路径 }); historyMiddleware(req, res, next); }, }, });
验证效果
启动Vite开发服务器后:
- 访问
localhost:5173/exp/test会加载/exp/index.html,由React路由处理该子路径 - 访问
localhost:5173/spa/abc会加载/spa/index.html - 其他路径默认加载根目录的
index.html
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

