Vite

Writing Vite plugins for development and builds

Follow Vite's plugin lifecycle across Rollup and Rolldown, then build a virtual module, development middleware, and HTML tag injection.

Writing Vite plugins for development and builds

I use a Vite plugin when a task belongs in module resolution, the development server, or the emitted HTML. The right hook depends on where the task needs to run.

What changes across the bundler generations

Vite 5 through 7 commonly used esbuild in development and Rollup for the production bundle. Vite 8 uses Rolldown as its bundler. Rolldown is written in Rust and shares tooling with the Oxc ecosystem. Its Rollup-compatible plugin interface carries over many plugins, while some behavior and implementation details still need migration checks. Vite 8 release notes

flowchart TD
    CODE["Application modules"] --> V7["Earlier Vite pipelines"]
    CODE --> V8["Vite 8 pipeline"]
    V7 --> ROLLUP["Rollup build"]
    V8 --> ROLLDOWN["Rolldown build"]
    ROLLUP --> PLUGINS["Bundler plugin hooks"]
    ROLLDOWN --> PLUGINS

Performance depends on the project. Native processing can reduce the cost of large module graphs. Work done inside a synchronous JavaScript plugin can still dominate the build. Measure the representative app and the plugins it actually loads.

Selecting hooks by the work they perform

A plugin has a name, and can constrain application with apply or adjust its order with enforce. config and configResolved handle configuration. configureServer is specific to the development server. transformIndexHtml works with HTML entries. handleHotUpdate participates in development updates.

flowchart TD
    CONFIG["Resolve configuration"] --> ENV{"Development or build?"}
    ENV -->|"Development"| SERVER["Configure server and updates"]
    ENV -->|"Build"| HTML["Transform HTML entries"]
    SERVER --> MOD["Resolve, load, and transform modules"]
    HTML --> MOD

The bundler-facing examples use resolveId to recognize an import, load to supply source, and transform to rewrite source when needed. Dev and production do not necessarily call every hook in the same conditions. Limit the plugin to the mode and IDs it understands.

Exposing build metadata through a virtual module

The example gives client code a virtual:build-info import. Internally the plugin resolves it to an ID with a null-byte prefix, then supplies generated module source. The prefix distinguishes an internal virtual ID from normal filesystem paths. A TypeScript declaration documents the data shape.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// plugins/buildInfoPlugin.ts
import type { Plugin } from 'vite';
import { execSync } from 'child_process';

export function buildInfoPlugin(): Plugin {
  const virtualModuleId = 'virtual:build-info';
  const resolvedVirtualModuleId = '\0' + virtualModuleId;

  let commitHash = 'unknown';
  try {
    commitHash = execSync('git rev-parse --short HEAD').toString().trim();
  } catch {
    commitHash = 'dev-workspace';
  }

  return {
    name: 'vite-plugin-build-info',

    // 1. Resolve the public virtual module ID.
    resolveId(id: string) {
      if (id === virtualModuleId) {
        return resolvedVirtualModuleId;
      }
      return null;
    },

    // 2. Supply source for the resolved virtual module.
    load(id: string) {
      if (id === resolvedVirtualModuleId) {
        const buildData = {
          commitHash,
          buildTime: new Date().toISOString(),
          nodeVersion: process.version,
          bundler: 'rolldown-ready',
          environment: process.env.NODE_ENV || 'development'
        };

        return `export default ${JSON.stringify(buildData, null, 2)};`;
      }
      return null;
    }
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/vite-env.d.ts
declare module 'virtual:build-info' {
  interface BuildInfo {
    commitHash: string;
    buildTime: string;
    nodeVersion: string;
    bundler: string;
    environment: string;
  }
  const buildInfo: BuildInfo;
  export default buildInfo;
}

// src/main.ts
import buildInfo from 'virtual:build-info';

console.log('App initialized with Build Info:', buildInfo);

Build output showing the virtual build-info module Figure 1. The client can import the generated build information without a source file at that path.

Treat values emitted in a client-side module as public. A commit hash and build time may be useful for diagnostics. Private environment variables belong outside the generated module.

Serving mock endpoints during local development

The middleware example attaches local routes in configureServer and limits the plugin to serve. Unrecognized requests continue to the rest of the dev server. Keep the route surface small and return a response shape that matches the feature under development.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// plugins/mockDevServerPlugin.ts
import type { Plugin, ViteDevServer } from 'vite';
import type { IncomingMessage, ServerResponse } from 'http';

export function mockDevServerPlugin(): Plugin {
  return {
    name: 'vite-plugin-mock-dev-server',
    // Apply only while the Vite development server is running.
    apply: 'serve',

    // Vite development server hook.
    configureServer(server: ViteDevServer) {
      server.middlewares.use((req: IncomingMessage, res: ServerResponse, next: () => void) => {
        // 1. Handle GET /api/mock/ping.
        if (req.method === 'GET' && req.url === '/api/mock/ping') {
          res.setHeader('Content-Type', 'application/json');
          res.statusCode = 200;
          res.end(
            JSON.stringify({
              status: 'success',
              message: 'pong',
              source: 'vite-plugin-mock-dev-server',
              serverTime: new Date().toISOString()
            })
          );
          return;
        }

        // 2. Handle POST /api/mock/users.
        if (req.method === 'POST' && req.url === '/api/mock/users') {
          let body = '';
          req.on('data', (chunk) => {
            body += chunk;
          });
          req.on('end', () => {
            try {
              const parsed = JSON.parse(body || '{}');
              res.setHeader('Content-Type', 'application/json');
              res.statusCode = 200;
              res.end(
                JSON.stringify({
                  code: 200,
                  data: {
                    id: 'usr_99812',
                    name: parsed.name || 'Anonymous',
                    role: parsed.role || 'Member',
                    createdAt: new Date().toISOString()
                  }
                })
              );
            } catch {
              res.statusCode = 400;
              res.end(JSON.stringify({ error: 'Invalid JSON payload' }));
            }
          });
          return;
        }

        // Pass unmatched requests to the next middleware.
        next();
      });
    }
  };
}

Response from the Vite mock development endpoint Figure 2. The development middleware returns a mock API response.

Use the mock for development feedback and verify the production API separately. Check normal and malformed input, unknown routes, and a production build to confirm the mock server is absent from the deployment.

Adding public metadata to the built HTML

The third plugin reads the resolved command and mode, then returns HTML tag descriptors. It inserts build metadata and, if configured for a production build, adds the analytics script. The final configuration registers the three plugins for the same app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// plugins/htmlEnvInjectPlugin.ts
import type { Plugin, HtmlTagDescriptor } from 'vite';

interface HtmlEnvInjectOptions {
  gaMeasurementId?: string;
  appVersion?: string;
}

export function htmlEnvInjectPlugin(options: HtmlEnvInjectOptions = {}): Plugin {
  let isProduction = false;

  return {
    name: 'vite-plugin-html-env-inject',

    // Read the resolved Vite command and mode.
    configResolved(config) {
      isProduction = config.command === 'build' && config.mode === 'production';
    },

    // Vite HTML entry transform.
    transformIndexHtml(html: string) {
      const tags: HtmlTagDescriptor[] = [];

      // 1. Insert public build metadata.
      tags.push(
        {
          tag: 'meta',
          attrs: { name: 'build-version', content: options.appVersion || 'v1.0.0' },
          injectTo: 'head'
        },
        {
          tag: 'meta',
          attrs: { name: 'build-environment', content: isProduction ? 'production' : 'development' },
          injectTo: 'head'
        }
      );

      // 2. Add the analytics tags only in the production build.
      if (isProduction && options.gaMeasurementId) {
        tags.push(
          {
            tag: 'script',
            attrs: {
              async: true,
              src: `https://www.googletagmanager.com/gtag/js?id=${options.gaMeasurementId}`
            },
            injectTo: 'head'
          },
          {
            tag: 'script',
            children: `
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${options.gaMeasurementId}');
            `,
            injectTo: 'head'
          }
        );
      }

      return {
        html,
        tags
      };
    }
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// vite.config.ts
import { defineConfig } from 'vite';
import { buildInfoPlugin } from './plugins/buildInfoPlugin';
import { mockDevServerPlugin } from './plugins/mockDevServerPlugin';
import { htmlEnvInjectPlugin } from './plugins/htmlEnvInjectPlugin';

export default defineConfig({
  plugins: [
    buildInfoPlugin(),
    mockDevServerPlugin(),
    htmlEnvInjectPlugin({
      gaMeasurementId: 'G-XXXXXXX',
      appVersion: 'v1.4.2'
    })
  ]
});

Emitted HTML containing the injected metadata and analytics tags Figure 3. The output HTML contains the tags selected for the production mode.

Use a known public analytics measurement identifier from trusted build configuration. Check the site’s Content Security Policy and deployment settings before enabling an inline script. Compare a dev request with the production output so environment gating is visible in both paths.

Verifying compatibility and hook cost

Test a plugin against the oldest and newest Vite versions you support. Use simple early returns for irrelevant source IDs. Move expensive filesystem reads out of per-module hooks where possible, and inspect timing on a cold build. Verify that a virtual import resolves, a mock route exists only during serve, and the built HTML has the intended tags.

Next Generation Frontend Tooling
This post is licensed under CC BY 4.0 by the author.