logo hsb.horse
← Back to blog index

Blog

My First Vite Plugin Implementation: Automatically Generate Build Metadata

How to plug custom logic into the Vite build lifecycle with the Vite Plugin API. Learn through a plugin that generates time-based semantic version metadata.

Published:

I tried using the Plugin API in Vite to hook custom processing into Vite’s build lifecycle.

Goal

I want to understand the Plugin API better.

Topic

Using a utility that generates a time-based semantic version, create and place a build metadata file in the public directory.

Plugin implementation

import { Plugin, ResolvedConfig } from "vite";
import { writeFile } from "node:fs/promises";
import { timeBasedSemanticVersion } from "./utils";
export function myPlugin(): Plugin {
let config: ResolvedConfig;
return {
name: "my-plugin",
configResolved(c) {
config = c;
},
closeBundle() {
const path = `${config.build.outDir}/version.json`;
const jsonStr = JSON.stringify({
ts: Date.now(),
version: timeBasedSemanticVersion(),
});
writeFile(path, jsonStr);
},
};
}

Points

  1. configResolved: Save config when the build configuration is finalized
  2. closeBundle: Generate the file when bundling is complete
  3. config.build.outDir: Refer to Vite’s output directory

Register the plugin in Vite config

import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { myPlugin } from "./my-plugin.ts";
export default defineConfig({
plugins: [svelte(), myPlugin()],
});

Summary

With the Vite Plugin API, it is easy to hook custom processing into the build process.

Automatically generating version information or build metadata makes deployment management and cache control easier.