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
- configResolved: Save
configwhen the build configuration is finalized - closeBundle: Generate the file when bundling is complete
- 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.
hsb.horse