String replacements in index.html in vite

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:

const transformHtmlPlugin = data => ({
    name: 'transform-html',
    transformIndexHtml: {
        enforce: 'pre',
        transform(html) {
            return html.replace(
                /<%=\s*(\w+)\s*%>/gi,
                (match, p1) => data[p1] || ''
            );
        }
    }
});

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!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)