React Vite项目中vite-plugin-rewrite-all插件为何在preview模式下失效?
Vite Preview模式下URL含点无法访问的解决办法
问题背景
React + Vite应用中,URL包含点(.)时无法正常访问,使用vite-plugin-rewrite-all插件在开发模式(npm run dev)下可正常解决,但执行npm run preview构建预览后,带点的URL依然无法访问,示例URL:
http://localhost:4173/dashboard/users/edit/cpt.americahttp://localhost:4173/dashboard/users/edit/john.doe
当前vite.config.mts配置:
import path from 'path'; import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import jsconfigPaths from 'vite-jsconfig-paths'; import pluginRewriteAll from 'vite-plugin-rewrite-all'; // ---------------------------------------------------------------------- export default defineConfig({ plugins: [react(), pluginRewriteAll(), jsconfigPaths()], base: process.env.VITE_APP_BASE_NAME, define: { global: 'window' }, resolve: { alias: [ { find: /^~(.+)/, replacement: path.join(process.cwd(), 'node_modules/$1') }, { find: /^src(.+)/, replacement: path.join(process.cwd(), 'src/$1') } ] }, server: { open: true, port: 4173 }, preview: { open: true, port: 4173 }, build: { outDir: 'myAPP', } });
解决办法
1. 手动配置Preview的路由重写规则
vite-plugin-rewrite-all默认仅对开发服务器生效,Preview模式需要单独配置路由重写,将非静态资源请求指向index.html(SPA应用的核心路由 fallback 逻辑)。修改vite.config.mts中的preview配置:
preview: { open: true, port: 4173, rewrites: [ // 通用规则:匹配所有非静态文件的请求,都转发到index.html { source: '!**/*.{js,css,html,png,jpg,jpeg,gif,svg,ico}', destination: '/index.html' } ] }
如果需要更精准匹配特定路径,也可以添加针对性规则:
rewrites: [ { source: '/dashboard/users/edit/:user', destination: '/index.html' }, // 通用兜底规则 { source: '!**/*.{js,css,html,png,jpg,jpeg,gif,svg,ico}', destination: '/index.html' } ]
2. 替换为支持Preview模式的插件
如果上述配置无效,可以尝试替换插件为vite-plugin-spa-fallback,它同时支持开发和预览模式的路由 fallback:
- 安装插件:
npm install vite-plugin-spa-fallback --save-dev - 修改
vite.config.mts的plugins数组:
import spaFallback from 'vite-plugin-spa-fallback'; export default defineConfig({ plugins: [react(), spaFallback(), jsconfigPaths()], // 其他配置保持不变 });
3. 自定义Preview服务器(备选方案)
如果以上方法都不生效,可以用Express搭建一个简单的自定义预览服务器,确保路由重写逻辑正确:
- 安装Express:
npm install express --save-dev - 在项目根目录创建
preview-server.js:
const express = require('express'); const path = require('path'); const app = express(); const port = 4173; // 托管build产物目录 app.use(express.static(path.join(__dirname, 'myAPP'))); // 所有非静态资源请求返回index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'myAPP', 'index.html')); }); app.listen(port, () => { console.log(`预览服务器运行在 http://localhost:${port}`); });
- 在
package.json中添加脚本:
"scripts": { "preview-custom": "node preview-server.js" }
- 执行
npm run preview-custom启动自定义预览服务器。
内容的提问来源于stack exchange,提问作者Ignatius Chandra
相关产品推荐
相关产品推荐

