Dmitry Sobolevsky
2 min readApr 26, 2024

Unlock Vite’s Power with custom plugins!

Today let’s create a very necessary and small plugin to save the version of your build in index.html file.

If you have many environments and you need to check often which version of your web application is deployed on which environment — then this is the article for you!

Photo by Johannes Plenio on Unsplash

Vite config

And so we have vite.config.ts for React application, actually it doesn’t matter what type of web application you are using with Vite — our new micro plugin will fit for all :)

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})

.env file

So, we will read environment variables from our environment or .env files that Vite supports out of the box.

For example, we can create a new .env file in the same folder as vite.config.ts.

VITE_BUILD_VERSION=5.0.1

.html changes

Let’s also add placeholder to index.html file for future replacement during build. I suggest adding this hidden span element to the very beginning of the body tag for easy viewing in Dev Tools Inspector.

  <body>
<span id="version" hidden>${version}</span>
....
</body>

New Plugin

We’re going to use transformIndexHtml method to change the contents of our .html file.
And so, our task is to find ${version} in the html stream and replace it with the current build version which can be in your environment variables during CI/CD job.

const versionInjector = (buildVersion: string) => {

return {
name: 'version-injector', // Name of the plugin
transformIndexHtml(html) {
const version = buildVersion || '0.0.0';

// Replace the placeholder with the actual version
return html.replace('${version}', version);
}
};
};

Updating vite.config.ts

And so our Vite config now looks like this!

import {defineConfig, loadEnv} from 'vite'
import react from '@vitejs/plugin-react'

export const versionInjector = (buildVersion: string) => {

return {
name: 'version-injector', // Name of the plugin
transformIndexHtml(html) {
const version = buildVersion || '0.0.0';

// Replace the placeholder with the actual version
return html.replace('${version}', version);
}
};
};

export default defineConfig(({mode}) => {
// loading env variables
const env = loadEnv(mode, process.cwd());

return {plugins: [react(), versionInjector(env.VITE_BUILD_VERSION)]};
});

Let’s now start our project and look at the beginning of the <body> tag.

Screenshot of DOM tree
Dev Tools Inspector

Congratulations the plugin is ready!

Conclusion

The point of this article was to show how easy and beautiful it is to make plugins for Vite and change literally anything while building an application.

And also if you are interested in this topic, I recommend you to study the source code of plugin-react.

Stay tuned!

Reach me on LinkedIn 🚀