admin管理员组

文章数量:1397093

I'm migrating a project from Webpack to Vite and trying to replicate this Webpack devServer configuration:

historyApiFallback: {
    rewrites: [
        {
            from: new RegExp('^' + appConfigs.managerContextPath + '.*$'),
            to: appConfigs.contextPath + 'manager.html'
        },
        {
            from: new RegExp('^' + appConfigs.contextPath + '.*$'),
            to: appConfigs.contextPath + 'index.html'
        }
    ]
}

I attempted the following Vite configuration:

export default defineConfig({
    root: path.resolve(__dirname, 'src'),
    base: '/',
    plugins: [
        react(),
    ],
    // appType: 'custom', // This ensures we're not handling HTML automatically
    build: {
        sourcemap: true,
        outDir: resolve(__dirname, 'bundles'),
        rollupOptions: {
            input: {
                app: resolve(__dirname, 'src/app.html'),
                arm: resolve(__dirname, 'src/arm.html'),
            }
        }
    },
});

With this, I can open /app and /arm, but navigating to /app/login results in a "No webpage found" error. What I Need: I want Vite to behave like Webpack's historyApiFallback, ensuring:

/app loads app.html, /arm loads arm.html,

Any subroutes like /app/login should still serve app.html

Any subroutes like /arm/settings should serve arm.html.

My Research:

I've looked into Vite's server options, specifically server.middlewareMode, but I’m not sure how to properly rewrite requests for different contexts. Has anyone done something similar in Vite? How can I configure Vite's dev server to handle this kind of routing logic??

I tried using a plugin for fallback, but when I do that, it just opens the raw HTML file and completely ignores my React app like it doesn’t hydrate or run the JS bundle. So the plugin approach doesn’t work for what I need, i'm looking for a proper solution that works with the actual built react app in production And here's a runnable example:

.md

discussion on vite github

本文标签: javascriptHow to Implement historyApiFallback Rewrites in ViteStack Overflow