vite-plugin-mock-replace

raw JSON →
0.0.3 verified Mon Apr 27 auth: no javascript

Vite plugin (0.0.3, early development) that replaces source files with mock implementations during testing (vitest, Storybook). Supports extension-based (my-file.ts → my-file.mock.ts) and directory-based (__mocks__/my-file.ts) overrides. Requires vite >=5.0.0 and vitest >=1.0.0 as peer dependencies. Lightweight alternative to manual module mocking with zero-config auto-resolution.

error Cannot find module 'vite-plugin-mock-replace'
cause Package was not installed (dev dependency missing).
fix
npm install -D vite-plugin-mock-replace
error Error: The plugin 'vite-plugin-mock-replace' requires Vite >=5.0.0
cause Using an older Vite version (<5.0.0).
fix
Update Vite: npm install vite@latest
error TypeError: mockReplace is not a function
cause Incorrect import: using named import instead of default.
fix
Change to: import mockReplace from 'vite-plugin-mock-replace'
breaking Requires Vite >=5.0.0 and Vitest >=1.0.0; older versions will fail to load the plugin.
fix Upgrade Vite to >=5.0.0 and Vitest to >=1.0.0.
gotcha Plugin modifies Vite's resolve logic; mock files must follow naming convention exactly (e.g., .mock.ts, not .spec.ts).
fix Ensure mock files are adjacent to source with .mock suffix or inside __mocks__ folder.
gotcha Only works during build/serve with Vite; not for Jest or other test runners.
fix Use only with vitest or Vite-based environments (Storybook).
npm install vite-plugin-mock-replace
yarn add vite-plugin-mock-replace
pnpm add vite-plugin-mock-replace

Minimal vitest configuration enabling mock file replacement for testing.

// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import mockReplace from 'vite-plugin-mock-replace';

export default defineConfig({
  plugins: [
    react(),
    mockReplace(), // auto-replaces files with .mock.ts or __mocks__/
  ],
  test: {
    globals: true,
    environment: 'node',
  },
});