npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

vite-plugin-automock

v1.0.3

Published

Effortless API mock auto-generation for legacy projects. No manual files, just automock!

Readme

vite-plugin-automock

Effortless API mock auto-generation for legacy projects. No manual files, just automock!


Features

  • 🚀 Automatically captures API requests and generates local mock data
  • 🏆 Perfect for legacy projects, easily backfill missing mocks
  • 🛠️ Supports manual mock file creation with a simple format
  • ⚡ Zero-config, plug-and-play
  • 🧩 Fully compatible with the Vite plugin ecosystem
  • 📦 Production-ready with client-side interceptor
  • 🎛️ Visual mock inspector panel

Installation

pnpm add -D vite-plugin-automock
# or
npm install --save-dev vite-plugin-automock
# or
yarn add -D vite-plugin-automock

Quick Start

1. Configure Vite Plugin

// vite.config.ts
import { automock } from 'vite-plugin-automock'

export default defineConfig({
  plugins: [
    automock({
      mockDir: 'mock',
      apiPrefix: '/api',
      bundleMockData: true,      // Bundle mock data for production
      productionMock: true,       // Enable mock in production
      proxyBaseUrl: 'https://api.example.com'
    })
  ]
})

2. Create Mock Files

// mock/users.ts
import { MockFileConfig } from 'vite-plugin-automock'

export default {
  enable: true,
  data: { users: [{ id: 1, name: 'Alice' }] },
  delay: 100,
  status: 200
} as MockFileConfig

3. Initialize Client Interceptor

For PureHttp wrapper:

// src/main.ts or src/api/index.ts
import {
  initMockInterceptorForPureHttp,
  setMockEnabled,
  registerHttpInstance
} from 'vite-plugin-automock/client'
import { http } from './http' // Your PureHttp instance

// Register your http instance
registerHttpInstance(http)

// Initialize mock interceptor
initMockInterceptorForPureHttp()
  .then(() => {
    console.log('[MockInterceptor] Initialized successfully')
  })
  .catch(error => {
    console.error('[MockInterceptor] Failed to initialize:', error)
  })

// Enable mock in development
if (import.meta.env.DEV) {
  setMockEnabled(true)
}

For plain Axios:

// src/main.ts
import { initMockInterceptor, setMockEnabled } from 'vite-plugin-automock/client'
import axios from 'axios'

// Initialize with axios instance
initMockInterceptor(axios)
  .then(() => {
    console.log('[MockInterceptor] Initialized successfully')
  })
  .catch(error => {
    console.error('[MockInterceptor] Failed to initialize:', error)
  })

// Enable mock in development
if (import.meta.env.DEV) {
  setMockEnabled(true)
}

Documentation

For detailed usage instructions, configuration options, and examples, see:

📚 Complete Usage Guide

Topics covered:

  • Development vs Production modes
  • Client interceptor configuration
  • Runtime mock toggle
  • Visual inspector
  • API reference
  • Common scenarios

Basic Usage (Development Mode)

Import and register the plugin in your vite.config.ts:

import { automock } from "vite-plugin-automock";

export default {
  plugins: [
    automock({
      proxyBaseUrl: "http://localhost:8888", // Required: Your API server URL
      mockDir: "mock", // Optional: Directory for mock files (default: 'mock')
      apiPrefix: "/api", // Optional: API prefix to intercept (default: '/api')
      pathRewrite: (path) => path, // Optional: Path rewrite function
      inspector: true, // Optional: Enable visual inspector (default: false)
    }),
  ],
};

With Custom Inspector Configuration

automock({
  proxyBaseUrl: "http://localhost:8888",
  inspector: {
    route: "/__inspector/", // Custom route for inspector UI
    enableToggle: true, // Allow toggling enable/disable
  },
});

Configuration Options

| Option | Type | Required | Default | Description | | -------------- | ----------------- | -------- | ---------------- | --------------------------------- | | proxyBaseUrl | string | ✅ | - | Base URL of your API server | | mockDir | string | ❌ | 'mock' | Directory to store mock files | | apiPrefix | string | ❌ | '/api' | API path prefix to intercept | | pathRewrite | function | ❌ | (path) => path | Function to rewrite request paths | | inspector | boolean | object | ❌ | false | Enable visual mock inspector UI |

Common Pitfalls

⚠️ Dual Proxy Configuration

Do NOT configure both Vite's server.proxy and automock's proxyBaseUrl for the same API prefix. This will cause conflicts and requests may hang.

❌ Wrong:

export default defineConfig({
  plugins: [
    automock({
      proxyBaseUrl: "http://localhost:8888",
      apiPrefix: "/api",
    })
  ],
  server: {
    proxy: {
      "/api": {  // ❌ CONFLICTS with automock
        target: "http://localhost:8888",
        changeOrigin: true,
      }
    }
  }
})

✅ Correct:

export default defineConfig({
  plugins: [
    automock({
      proxyBaseUrl: "http://localhost:8888",
      apiPrefix: "/api",
    })
  ],
  // ✅ Remove server.proxy or use a different prefix
})

The plugin will automatically warn you if a conflicting proxy configuration is detected.

Inspector Options

When inspector is an object, you can customize:

| Option | Type | Default | Description | | -------------- | ------- | ------------ | ---------------------------------- | | route | string | '/__mock/' | Route path for the inspector UI | | enableToggle | boolean | true | Allow toggling mock enable/disable |

Mock Inspector 🎨

NEW! Visual interface to manage your mock files:

automock({
  proxyBaseUrl: "http://localhost:8888",
  inspector: true, // Enable inspector UI
});

Then visit http://localhost:5173/__mock/ to:

  • 📋 Browse all mock files organized by URL
  • 🎛️ Toggle mock enable/disable status
  • ⏱️ Adjust response delay and status codes
  • ✏️ Edit JSON response data directly
  • 💾 Save changes with a single click

Inspector Demo

How It Works

  1. Request Interception: The plugin intercepts all requests matching the apiPrefix
  2. Mock Check: Checks if a corresponding mock file exists
  3. Conditional Response:
    • If mock exists → Returns mock data
    • If mock doesn't exist → Proxies to real API and saves response as mock
  4. Auto-Generation: Real API responses are automatically saved as mock files
  5. Hot Reloading: Changes to mock files are automatically detected and reloaded
  6. Visual Inspector: Manage and edit mocks through the web UI

Mock File Structure

Mock files are organized by URL path and HTTP method:

mock/
├── api/
│   ├── users/
│   │   ├── get.js     # GET /api/users
│   │   └── post.js    # POST /api/users
│   └── items/
│       ├── get.js     # GET /api/items
│       └── post.js    # POST /api/items

Each mock file exports an object with this structure:

/**
 * Mock data for /api/users (GET)
 * Generated at 2025-01-11T10:30:00.000Z
 */
export default {
  enable: false, // Whether to use this mock (default: false)
  data: {
    // Response data
    code: 0,
    message: "success",
    data: [
      { id: 1, name: "User 1" },
      { id: 2, name: "User 2" },
    ],
  },
  delay: 0, // Artificial delay in milliseconds
  status: 200, // HTTP status code
};

Quick Start

  1. Try the Example:

    pnpm run example

    This starts the playground with a demo API server.

  2. Manual Setup:

    # Install the plugin
    pnpm add -D vite-plugin-automock
    
    # Add to your vite.config.js
    import { automock } from "vite-plugin-automock";
    
    export default {
      plugins: [
        automock({
          proxyBaseUrl: "http://localhost:8888"
        })
      ]
    };
  3. Start Development:

    • Start your API server
    • Start Vite dev server
    • Make API calls from your frontend
    • Check the mock directory for generated files

Comparison with Traditional Mock Plugins

| Feature | Traditional Mock Plugins | vite-plugin-automock | | ---------------------- | ------------------------ | -------------------- | | Auto backfill | ❌ | ✅ | | Legacy project support | ❌ | ✅ | | Manual mock files | ✅ | ✅ | | Config complexity | High | Very low | | Zero setup | ❌ | ✅ | | Real API integration | ❌ | ✅ |

When to Use

  • Legacy Projects: Quickly add mock capability to existing projects
  • API Development: Test frontend while backend is being developed
  • Offline Development: Work without internet or when APIs are unavailable
  • Testing: Consistent test data without external dependencies
  • Demo/Presentation: Reliable demo data that doesn't change

Advanced Usage

Custom Path Rewriting

automock({
  proxyBaseUrl: "http://api.example.com",
  pathRewrite: (path) => {
    // Remove /api prefix when proxying
    return path.replace(/^\/api/, "");
  },
});

Conditional Mock Enabling

// In your mock file
export default {
  enable: process.env.NODE_ENV === "development",
  data: {
    /* mock data */
  },
};

Dynamic Mock Data

// In your mock file
export default {
  enable: true,
  data: () => ({
    timestamp: new Date().toISOString(),
    randomId: Math.floor(Math.random() * 1000),
  }),
};

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

License

ISC