Force host part in BASE url when using Vite's development server
I have a somewhat non-conventional setup where I use a Vite/Vue SSR server for template rendering behind a Django server. I.e. Django calls node, gets html back, and sends it back to the browser. I encountered a problem with Vite's dev server in that it doesn't respect a full BASE
url like https://bar.com/foo/
(it strips out the origin part, which is documented behavior). Without the origin part, however, the generated html and other assets contain urls that the browser treats as relative to the origin of the Django server, which obviously doesn't work. Is there a way to force Vite to include the origin in the BASE
url, or is my only option to proxy back to the Vite server from Django?
I got this working by adding a <base>
tag, taking special care to place it right after the <head>
tag. Otherwise, Vite inserted its client script tag before the <base>
tag, but the <base>
tag only applies to elements that come after it. There's an explicit warning to keep this in mind in the MDN docs for <base>:
Warning: A
<base>
element must have an href attribute, a target attribute, or both. If at least one of these attributes are specified, the<base>
element must come before other elements with attribute values that are URLs, such as a<link>
's href attribute.
To add the <base>
tag before Vite's client script tag, I used a Vite transformIndexHtml plugin:
plugins: [
vue(),
{
name: 'vite-client-script-transform',
transformIndexHtml(html: string) {
return html.replace(
'<head>',
`<head><base href="http://localhost:5173" />`,
)
}
}
],