vite-plugin-automock
v1.0.3
Published
Effortless API mock auto-generation for legacy projects. No manual files, just automock!
Maintainers
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-automockQuick 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 MockFileConfig3. 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:
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
How It Works
- Request Interception: The plugin intercepts all requests matching the
apiPrefix - Mock Check: Checks if a corresponding mock file exists
- Conditional Response:
- If mock exists → Returns mock data
- If mock doesn't exist → Proxies to real API and saves response as mock
- Auto-Generation: Real API responses are automatically saved as mock files
- Hot Reloading: Changes to mock files are automatically detected and reloaded
- 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/itemsEach 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
Try the Example:
pnpm run exampleThis starts the playground with a demo API server.
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" }) ] };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
