All files / src/vite build-only.ts

100% Statements 21/21
100% Branches 10/10
100% Functions 3/3
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    2x 47x   47x 47x   47x 65x 18x 18x 6x 6x   12x 6x 3x       47x     47x       6x 6x 1x       47x    
import type { Plugin } from "vite";
 
export function buildOnly(plugin: Plugin | { name: string }): Plugin {
  let serve = false;
 
  const record = plugin as Record<string, unknown>;
  const wrapped: Record<string, unknown> = { name: record.name };
 
  for (const key of Object.keys(record)) {
    if (key === "name") continue;
    const value = record[key];
    if (typeof value !== "function") {
      wrapped[key] = value;
      continue;
    }
    wrapped[key] = function (this: unknown, ...args: unknown[]) {
      if (serve) return;
      return value.apply(this, args);
    };
  }
 
  const innerConfigResolved = wrapped.configResolved as
    | ((...args: unknown[]) => unknown)
    | undefined;
  wrapped.configResolved = function (
    this: unknown,
    config: { command: string },
  ) {
    serve = config.command === "serve";
    if (!serve && innerConfigResolved) {
      return innerConfigResolved.call(this, config);
    }
  };
 
  return wrapped as unknown as Plugin;
}