Skip to content

Instantly share code, notes, and snippets.

@emma-k-alexandra
Last active September 26, 2023 12:33
Show Gist options
  • Save emma-k-alexandra/47ef18239e8a1e517160aff591e8132d to your computer and use it in GitHub Desktop.
Save emma-k-alexandra/47ef18239e8a1e517160aff591e8132d to your computer and use it in GitHub Desktop.
Vite multi-page app trailing slash dev server workaround for https://github.com/vitejs/vite/issues/6596
/**
* Forwards routes in the given list to a route with a trailing slash in the dev server
* Useful for multi page vite apps where all rollup inputs are known.
*
* Vite fix is upcoming, which will make this plugin unnecessary
* https://github.com/vitejs/vite/issues/6596
*/
export default routes => ({
name: 'forward-to-trailing-slash',
configureServer(server) {
server.middlewares.use((req, _res, next) => {
const requestURLwithoutLeadingSlash = req.url.substring(1)
if (routes.includes(requestURLwithoutLeadingSlash)) {
req.url = `${req.url}/`
}
next()
})
}
})
/**
* Example vite.config.js using forwardToTrailingSlash plugin
*/
import { defineConfig } from 'vite'
import forwardToTrailingSlashPlugin from './forward-to-trailing-slash-plugin.js'
const build = {
rollupOptions: {
input: {
main: new URL('./index.html', import.meta.url).href,
photography: new URL('./photography/index.html', import.meta.url).href
}
}
}
export default defineConfig({
build,
plugins: [
forwardToTrailingSlashPlugin(Object.keys(build.rollupOptions.input))
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment