Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replacements in index.html in vite

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

like image 304
v-moe Avatar asked Aug 31 '25 15:08

v-moe


1 Answers

Update 2023-03-20:

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!

like image 128
Brother Woodrow Avatar answered Sep 05 '25 02:09

Brother Woodrow