I am trying to inject some strings into the index.html of a Vite app (using vue3 template). In a vue-cli project for example we would have
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
What is the Vite way to do that? (I know that BASE_URL is just '/' in this case. I am asking for the general solution) I would be fine with a solution that covers environment variables only, but it would be great to know an even more general solution that can use JS code as in
<title><%= htmlWebpackPlugin.options.title %></title>
And I would really appreciate a solution that doesn't require installing an npm package
Vite supports HTML Env replacement out of the box starting with version 4.2! So if that's all you're looking for, you should be set.
Older answer:
Wanted to do the same for a project. Used vite-plugin-html
for a bit, but I ran into an issue with the plugin and the author of the plugin seems to have stopped maintaining it, so I had to look into an alternative solution.
Luckily this is easy enough, as Vite has a hook for it.
So I ended up writing this tiny plugin (just remove the TypeScript if you don't use that):
const transformHtmlPlugin = (data: Record<string, string>): Plugin => ({
name: 'transform-html',
transformIndexHtml: {
order: 'pre',
handler(html: string) {
return html.replace(
/<%=\s*(\w+)\s*%>/gi,
(match, p1) => data[p1] || ''
);
}
}
});
(Updated for Vite 5 on 2025-01-11)
In the Vite config, just add it to the plugins array and pass it key/value pairs of things you'd like to be replaced in the HTML:
plugins: [transformHtmlPlugin({ key: 'value' })]
Then in your index.html
, add the tags like in the original question: <%= key %>
, and they will be replaced by whatever you passed into the plugin.
If you wanted to pass in all of your env variables, get them using loadEnv
(example is in v-moe's post) and just unpack the object: transformHtmlPlugin({ ...env })
.
So that's how I solved my issue. Maybe it's useful to someone out there!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With