0
Vite · Advanced Vite
New technique
Anatomy of a plugin
Time to forge your own tools. A Vite plugin is just an object with a name and some hooks.
By convention, a plugin is a function that returns an object, so users can pass options: plugins: [forgeBanner()]. The object needs a name (shown in warnings and errors) and one or more hooks: methods Vite calls at fixed moments.
transform is called for every module, with its code and its id (usually the file path). Return new code to change it. Return nothing and the module passes through untouched, so always check the id first: you rarely want to change every file.
import type { Plugin } from "vite";
export default function forgeBanner(): Plugin {
return {
name: "forge-banner",
transform(code, id) {
if (!id.endsWith(".ts")) return;
return "/* forged by Brunn */ " + code;
},
};
}