Last active
September 26, 2023 12:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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() | |
}) | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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