Vite

Injecting build metadata with Vite virtual modules

Use resolveId and load to expose typed build metadata as a virtual ES module without writing generated source files into the working tree.

Injecting build metadata with Vite virtual modules

The UI and error reports needed a Git revision and build time. I switched from generating metadata files to a typed Vite virtual module, so the app can import the data without a separate fetch or a generated file on disk.

Replacing the generated file

A common build script writes a JSON or TypeScript file immediately before the bundler runs. That works when the script and bundler agree on the path and timing.

1
2
# Example of writing temporary metadata to disk
git rev-parse HEAD > src/generated-build-info.json

The generated file introduces several maintenance costs. If it escapes .gitignore, the working tree can gain a machine-specific diff. An extra write is also visible to local file watchers, which can trigger HMR or a repeated build when metadata generation runs in response to changes. In a container, the source directory may be mounted read-only.

A virtual module serves data through Vite’s module resolution and loading pipeline. The application can use a normal static import. The plugin produces the module source as a string when it is needed, and the output contains the generated values.

Using separate public and internal IDs

The public import uses virtual:build-meta. resolveId maps it to an internal identifier prefixed with a null byte, written as \0virtual:build-meta in JavaScript. load recognizes that resolved ID and returns JavaScript source.

sequenceDiagram
    autonumber
    actor App as Client main.ts
    participant Vite as Vite resolver
    participant Plugin as Plugin
    participant FS as Filesystem
    App->>Vite: import meta from 'virtual:build-meta'
    Vite->>Plugin: resolveId('virtual:build-meta')
    Note over Plugin: Recognize import and prefix the internal ID
    Plugin-->>Vite: Return internal ID
    Note over Vite: Skip filesystem lookup for the internal ID
    Vite->>Plugin: load('\0virtual:build-meta')
    Note over Plugin: Generate JavaScript with build metadata
    Plugin-->>Vite: 'export const gitCommit = "7b4e9f...";'
    Vite-->>App: Return the ES module

The null-byte convention distinguishes a module supplied by a plugin from a path on disk. Other plugins can skip filesystem operations for such IDs. Vite encodes IDs for browser requests and decodes them before sending them through the plugin pipeline. The public API uses a readable virtual: namespace and never requires consumers to import a null byte. Vite virtual module convention

A narrow ID check is important in both hooks. Other plugins own their own virtual identifiers. A shared prefix is useful when one plugin supplies several related imports, but it should still have a namespace specific to the feature.

Building the metadata module

The plugin reads Git metadata and combines it with its configuration and the build timestamp. It constructs a stable object for the loaded module and serializes values as JavaScript-safe literals. The file is never written to the project directory.

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
69
70
71
72
73
74
75
// plugins/vite-plugin-build-meta.ts
import type { Plugin } from 'vite';
import { execSync } from 'node:child_process';

export interface BuildMetaOptions {
  features?: Record<string, boolean>;
}

export function buildMetaPlugin(options: BuildMetaOptions = {}): Plugin {
  // Public import ID
  const virtualModuleId = 'virtual:build-meta';
  // Internal ID prefixed with a null byte
  const resolvedVirtualModuleId = '\0' + virtualModuleId;

  // Read Git metadata with a fallback
  const getGitInfo = () => {
    try {
      const commit = execSync('git rev-parse --short HEAD').toString().trim();
      const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
      return { commit, branch };
    } catch {
      return { commit: 'unknown-commit', branch: 'unknown-branch' };
    }
  };

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

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

    // 2. Generate virtual module source in memory
    load(id) {
      if (id === resolvedVirtualModuleId) {
        const { commit, branch } = getGitInfo();
        const buildTime = new Date().toISOString();
        const nodeVersion = process.version;

        const metadata = {
          gitCommit: commit,
          gitBranch: branch,
          buildTimestamp: buildTime,
          builtBy: process.env.USER || 'ci-runner',
          nodeVersion: nodeVersion,
          viteVersion: '5.4.8',
          environment: process.env.NODE_ENV || 'production',
          features: options.features || {
            analytics: true,
            debugPanel: false,
            mockApi: false,
          },
        };

        // Offer named exports for tree shaking and a default export for the complete object
        return `
          export const gitCommit = ${JSON.stringify(metadata.gitCommit)};
          export const gitBranch = ${JSON.stringify(metadata.gitBranch)};
          export const buildTimestamp = ${JSON.stringify(metadata.buildTimestamp)};
          export const builtBy = ${JSON.stringify(metadata.builtBy)};
          export const nodeVersion = ${JSON.stringify(metadata.nodeVersion)};
          export const features = ${JSON.stringify(metadata.features)};

          const buildMeta = ${JSON.stringify(metadata)};
          export default buildMeta;
        `;
      }
      return null;
    },
  };
}

A named export makes it easier for the bundler to remove unreferenced values. The default export is useful when a consumer needs the complete metadata object. Importing it and passing the whole object to another function may keep fields that would disappear with selective named imports.

Since there is no physical .ts file, TypeScript also needs an ambient module declaration. Keep its fields in sync with the plugin output and make sure tsconfig.json includes the declaration file.

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
// src/virtual-modules.d.ts
declare module 'virtual:build-meta' {
  export interface BuildFeatures {
    analytics: boolean;
    debugPanel: boolean;
    mockApi: boolean;
    [key: string]: boolean;
  }

  export interface BuildMeta {
    gitCommit: string;
    gitBranch: string;
    buildTimestamp: string;
    builtBy: string;
    nodeVersion: string;
    viteVersion: string;
    environment: string;
    features: BuildFeatures;
  }

  export const gitCommit: string;
  export const gitBranch: string;
  export const buildTimestamp: string;
  export const builtBy: string;
  export const nodeVersion: string;
  export const features: BuildFeatures;

  const buildMeta: BuildMeta;
  export default buildMeta;
}

Registering and checking the module

Register the plugin in vite.config.ts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// vite.config.ts
import { defineConfig } from 'vite';
import { buildMetaPlugin } from './plugins/vite-plugin-build-meta';

export default defineConfig({
  plugins: [
    buildMetaPlugin({
      features: {
        analytics: true,
        debugPanel: false,
        mockApi: false,
      },
    }),
  ],
});

The application then imports its build data just like any other module.

1
2
3
4
5
6
// src/main.ts
import buildMeta, { gitCommit, buildTimestamp } from 'virtual:build-meta';

console.log('[runtime] Loading virtual module: virtual:build-meta');
console.log(`Current Commit: ${gitCommit} (Built at: ${buildTimestamp})`);
console.table(buildMeta);

Runtime evaluation of the virtual build-meta module Figure 1. The client reads the build metadata from its module import.

The captured example initialized in under 12 ms. That is an observation from this run rather than a general performance target. In production, the metadata travels with the generated JavaScript and never needs a separate runtime metadata request. In development, Vite may serve the virtual module through its normal module request pipeline.

Production output showing virtual module values inlined in a chunk Figure 2. Inspecting the generated JavaScript for the retained metadata.

The example generated around 284 bytes of module source before bundling. Inspect the relevant dist/assets/index-*.js chunk after vite build. Used constants may be inlined and unused named exports can be removed. Whether all unused fields disappear also depends on how the module is imported and consumed.

Invalidation and what belongs in metadata

Use a distinct virtual: public name to avoid collisions. Query strings can select inputs, such as virtual:icon?name=check, as long as parsing and allowed values stay under the plugin’s control. Where the underlying data changes during development, invalidate the resolved module in the appropriate graph and trigger HMR or a reload. Reading Git once at plugin startup is sufficient for a reproducible build and can be stale after a branch switch in a long-lived dev process.

Every value exposed to a browser module is public. Include a revision or a public feature flag and keep credentials, private CI details, and internal paths out of the returned source.

  • Build from a checkout with Git metadata and from a source archive where Git is unavailable.
  • Check that selective imports retain only the fields your consumer needs.
  • Confirm that branch or source changes invalidate a development-only snapshot if the application expects live metadata.
This post is licensed under CC BY 4.0 by the author.