vite-plugin-automock 1.1.4 → 1.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +250 -232
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,13 +6,14 @@ Effortless API mock auto-generation for legacy projects. No manual files, just a
|
|
|
6
6
|
|
|
7
7
|
## Features
|
|
8
8
|
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
9
|
+
- Automatically captures API requests and generates local mock data
|
|
10
|
+
- Perfect for legacy projects, easily backfill missing mocks
|
|
11
|
+
- Supports manual mock file creation with a simple format
|
|
12
|
+
- Fine-grained control: enable/disable mock, proxy, and capture independently
|
|
13
|
+
- Visual mock inspector panel for managing mock files
|
|
14
|
+
- Production-ready with client-side interceptor (Axios / PureHttp)
|
|
15
|
+
- Fully compatible with the Vite plugin ecosystem
|
|
16
|
+
- Zero-config, plug-and-play
|
|
16
17
|
|
|
17
18
|
## Installation
|
|
18
19
|
|
|
@@ -26,8 +27,6 @@ yarn add -D vite-plugin-automock
|
|
|
26
27
|
|
|
27
28
|
## Quick Start
|
|
28
29
|
|
|
29
|
-
### 1. Configure Vite Plugin
|
|
30
|
-
|
|
31
30
|
```typescript
|
|
32
31
|
// vite.config.ts
|
|
33
32
|
import { automock } from 'vite-plugin-automock'
|
|
@@ -35,36 +34,150 @@ import { automock } from 'vite-plugin-automock'
|
|
|
35
34
|
export default defineConfig({
|
|
36
35
|
plugins: [
|
|
37
36
|
automock({
|
|
37
|
+
proxyBaseUrl: 'https://api.example.com', // Required: your API server URL
|
|
38
|
+
})
|
|
39
|
+
]
|
|
40
|
+
})
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
That's it! The plugin will:
|
|
44
|
+
|
|
45
|
+
1. Intercept requests matching `apiPrefix` (default `/api`)
|
|
46
|
+
2. Return mock data if a mock file exists
|
|
47
|
+
3. Proxy to `proxyBaseUrl` and auto-save the response as a mock file
|
|
48
|
+
|
|
49
|
+
## Configuration Options
|
|
50
|
+
|
|
51
|
+
### Plugin Options
|
|
52
|
+
|
|
53
|
+
| Option | Type | Required | Default | Description |
|
|
54
|
+
| ------ | ---- | -------- | ------- | ----------- |
|
|
55
|
+
| `proxyBaseUrl` | `string` | Yes | - | Base URL of your API server |
|
|
56
|
+
| `mockDir` | `string` | No | `'mock'` | Directory to store mock files |
|
|
57
|
+
| `apiPrefix` | `string` | No | `'/api'` | API path prefix to intercept |
|
|
58
|
+
| `pathRewrite` | `(path: string) => string` | No | `(path) => path` | Function to rewrite request paths |
|
|
59
|
+
| `enabled` | `boolean` | No | `true` | Global switch. When `false`, all requests pass through without mock handling |
|
|
60
|
+
| `proxy` | `boolean` | No | `true` | Whether to proxy unmatched requests to `proxyBaseUrl` |
|
|
61
|
+
| `capture` | `boolean` | No | `true` | Whether to auto-capture proxy responses and save as mock files |
|
|
62
|
+
| `productionMock` | `boolean \| 'auto'` | No | `false` | Enable mock in production mode |
|
|
63
|
+
| `inspector` | `boolean \| InspectorOptions` | No | `false` | Enable visual mock inspector UI |
|
|
64
|
+
|
|
65
|
+
### Bundle Options
|
|
66
|
+
|
|
67
|
+
These options are available when using the `automock()` function (which includes bundle support):
|
|
68
|
+
|
|
69
|
+
| Option | Type | Default | Description |
|
|
70
|
+
| ------ | ---- | ------- | ----------- |
|
|
71
|
+
| `bundleMockData` | `boolean` | `true` | Whether to bundle mock data for production |
|
|
72
|
+
| `bundleOutputPath` | `string` | `'public/mock-data.json'` | Output path for the mock bundle file |
|
|
73
|
+
|
|
74
|
+
### Inspector Options
|
|
75
|
+
|
|
76
|
+
When `inspector` is an object:
|
|
77
|
+
|
|
78
|
+
| Option | Type | Default | Description |
|
|
79
|
+
| ------ | ---- | ------- | ----------- |
|
|
80
|
+
| `route` | `string` | `'/__mock/'` | Route path for the inspector UI |
|
|
81
|
+
| `enableToggle` | `boolean` | `true` | Allow toggling mock enable/disable in the UI |
|
|
82
|
+
|
|
83
|
+
### Full Configuration Example
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
import { automock } from 'vite-plugin-automock'
|
|
87
|
+
|
|
88
|
+
export default defineConfig({
|
|
89
|
+
plugins: [
|
|
90
|
+
automock({
|
|
91
|
+
// Basic
|
|
92
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
38
93
|
mockDir: 'mock',
|
|
39
94
|
apiPrefix: '/api',
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
95
|
+
pathRewrite: (path) => path.replace(/^\/api/, ''),
|
|
96
|
+
|
|
97
|
+
// Fine-grained control
|
|
98
|
+
enabled: true,
|
|
99
|
+
proxy: true,
|
|
100
|
+
capture: true,
|
|
101
|
+
|
|
102
|
+
// Production
|
|
103
|
+
productionMock: 'auto',
|
|
104
|
+
bundleMockData: true,
|
|
105
|
+
bundleOutputPath: 'public/mock-data.json',
|
|
106
|
+
|
|
107
|
+
// Inspector
|
|
108
|
+
inspector: {
|
|
109
|
+
route: '/__mock/',
|
|
110
|
+
enableToggle: true,
|
|
111
|
+
},
|
|
43
112
|
})
|
|
44
113
|
]
|
|
45
114
|
})
|
|
46
115
|
```
|
|
47
116
|
|
|
48
|
-
|
|
117
|
+
## Fine-grained Control
|
|
118
|
+
|
|
119
|
+
The `enabled`, `proxy`, and `capture` options provide independent control over the plugin's behavior:
|
|
120
|
+
|
|
121
|
+
### Record-only Mode
|
|
122
|
+
|
|
123
|
+
Proxy to the backend and capture responses, but don't intercept requests with existing mocks:
|
|
49
124
|
|
|
50
125
|
```typescript
|
|
51
|
-
|
|
52
|
-
|
|
126
|
+
automock({
|
|
127
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
128
|
+
enabled: false, // Don't intercept
|
|
129
|
+
proxy: true, // Proxy to backend
|
|
130
|
+
capture: true, // Save responses as mock files
|
|
131
|
+
})
|
|
132
|
+
```
|
|
53
133
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
134
|
+
### Mock-only Mode
|
|
135
|
+
|
|
136
|
+
Only return mock data, never proxy to backend. Useful when you want strict offline development:
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
automock({
|
|
140
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
141
|
+
enabled: true, // Intercept requests
|
|
142
|
+
proxy: false, // Don't proxy to backend
|
|
143
|
+
capture: false, // Don't save new mocks
|
|
144
|
+
})
|
|
60
145
|
```
|
|
61
146
|
|
|
62
|
-
###
|
|
147
|
+
### Pure Proxy Mode
|
|
63
148
|
|
|
64
|
-
|
|
149
|
+
Bypass all mock handling, just proxy to backend:
|
|
65
150
|
|
|
66
151
|
```typescript
|
|
67
|
-
|
|
152
|
+
automock({
|
|
153
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
154
|
+
enabled: false, // Don't intercept
|
|
155
|
+
proxy: true, // Proxy to backend
|
|
156
|
+
capture: false, // Don't save mocks
|
|
157
|
+
})
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Default Mode (Recommended)
|
|
161
|
+
|
|
162
|
+
All features enabled - mock first, proxy fallback, auto-capture:
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
automock({
|
|
166
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
167
|
+
// enabled: true (default)
|
|
168
|
+
// proxy: true (default)
|
|
169
|
+
// capture: true (default)
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Client API Reference
|
|
174
|
+
|
|
175
|
+
The client-side interceptor is used for **production mode** mock support. Import from `vite-plugin-automock/client`.
|
|
176
|
+
|
|
177
|
+
### For PureHttp Wrapper
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
// src/main.ts
|
|
68
181
|
import {
|
|
69
182
|
initMockInterceptorForPureHttp,
|
|
70
183
|
setMockEnabled,
|
|
@@ -77,12 +190,8 @@ registerHttpInstance(http)
|
|
|
77
190
|
|
|
78
191
|
// Initialize mock interceptor
|
|
79
192
|
initMockInterceptorForPureHttp()
|
|
80
|
-
.then(() =>
|
|
81
|
-
|
|
82
|
-
})
|
|
83
|
-
.catch(error => {
|
|
84
|
-
console.error('[MockInterceptor] Failed to initialize:', error)
|
|
85
|
-
})
|
|
193
|
+
.then(() => console.log('[MockInterceptor] Initialized'))
|
|
194
|
+
.catch(error => console.error('[MockInterceptor] Failed:', error))
|
|
86
195
|
|
|
87
196
|
// Enable mock in development
|
|
88
197
|
if (import.meta.env.DEV) {
|
|
@@ -90,167 +199,94 @@ if (import.meta.env.DEV) {
|
|
|
90
199
|
}
|
|
91
200
|
```
|
|
92
201
|
|
|
93
|
-
For
|
|
202
|
+
### For Plain Axios
|
|
94
203
|
|
|
95
204
|
```typescript
|
|
96
205
|
// src/main.ts
|
|
97
206
|
import { initMockInterceptor, setMockEnabled } from 'vite-plugin-automock/client'
|
|
98
207
|
import axios from 'axios'
|
|
99
208
|
|
|
100
|
-
// Initialize with axios instance
|
|
101
209
|
initMockInterceptor(axios)
|
|
102
|
-
.then(() =>
|
|
103
|
-
|
|
104
|
-
})
|
|
105
|
-
.catch(error => {
|
|
106
|
-
console.error('[MockInterceptor] Failed to initialize:', error)
|
|
107
|
-
})
|
|
210
|
+
.then(() => console.log('[MockInterceptor] Initialized'))
|
|
211
|
+
.catch(error => console.error('[MockInterceptor] Failed:', error))
|
|
108
212
|
|
|
109
|
-
// Enable mock in development
|
|
110
213
|
if (import.meta.env.DEV) {
|
|
111
214
|
setMockEnabled(true)
|
|
112
215
|
}
|
|
113
216
|
```
|
|
114
217
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
For detailed usage instructions, configuration options, and examples, see:
|
|
118
|
-
|
|
119
|
-
**[📚 Complete Usage Guide](./docs/USAGE_GUIDE.md)**
|
|
120
|
-
|
|
121
|
-
Topics covered:
|
|
122
|
-
- Development vs Production modes
|
|
123
|
-
- Client interceptor configuration
|
|
124
|
-
- Runtime mock toggle
|
|
125
|
-
- Visual inspector
|
|
126
|
-
- API reference
|
|
127
|
-
- Common scenarios
|
|
128
|
-
|
|
129
|
-
---
|
|
130
|
-
|
|
131
|
-
## Basic Usage (Development Mode)
|
|
132
|
-
|
|
133
|
-
Import and register the plugin in your `vite.config.ts`:
|
|
218
|
+
### Client Exports
|
|
134
219
|
|
|
135
|
-
|
|
136
|
-
|
|
220
|
+
| Export | Type | Description |
|
|
221
|
+
| ------ | ---- | ----------- |
|
|
222
|
+
| `initMockInterceptor` | `(axios: AxiosInstance) => Promise<void>` | Initialize interceptor with an Axios instance |
|
|
223
|
+
| `initMockInterceptorForPureHttp` | `() => Promise<void>` | Initialize interceptor for PureHttp (call `registerHttpInstance` first) |
|
|
224
|
+
| `registerHttpInstance` | `(http: { constructor: { axiosInstance: AxiosInstance } }) => void` | Register a PureHttp instance |
|
|
225
|
+
| `setMockEnabled` | `(enabled: boolean) => void` | Enable/disable mock at runtime |
|
|
226
|
+
| `isMockEnabled` | `() => boolean` | Check if mock is currently enabled |
|
|
227
|
+
| `loadMockData` | `() => Promise<Record<string, MockBundleData>>` | Load mock data from the bundled JSON file |
|
|
228
|
+
| `createMockInterceptor` | `(options: MockInterceptorOptions) => MockInterceptor` | Create a custom interceptor instance |
|
|
137
229
|
|
|
138
|
-
|
|
139
|
-
plugins: [
|
|
140
|
-
automock({
|
|
141
|
-
proxyBaseUrl: "http://localhost:8888", // Required: Your API server URL
|
|
142
|
-
mockDir: "mock", // Optional: Directory for mock files (default: 'mock')
|
|
143
|
-
apiPrefix: "/api", // Optional: API prefix to intercept (default: '/api')
|
|
144
|
-
pathRewrite: (path) => path, // Optional: Path rewrite function
|
|
145
|
-
inspector: true, // Optional: Enable visual inspector (default: false)
|
|
146
|
-
}),
|
|
147
|
-
],
|
|
148
|
-
};
|
|
149
|
-
```
|
|
230
|
+
### MockInterceptorOptions
|
|
150
231
|
|
|
151
|
-
|
|
232
|
+
```typescript
|
|
233
|
+
interface MockInterceptorOptions {
|
|
234
|
+
mockData: Record<string, MockBundleData>
|
|
235
|
+
enabled?: boolean | (() => boolean)
|
|
236
|
+
onMockHit?: (url: string, method: string, mock: MockBundleData) => void
|
|
237
|
+
onBypass?: (url: string, method: string, reason: string) => void
|
|
238
|
+
}
|
|
152
239
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
});
|
|
240
|
+
interface MockBundleData {
|
|
241
|
+
enable: boolean
|
|
242
|
+
data: unknown
|
|
243
|
+
delay?: number
|
|
244
|
+
status?: number
|
|
245
|
+
isBinary?: boolean
|
|
246
|
+
}
|
|
161
247
|
```
|
|
162
248
|
|
|
163
|
-
##
|
|
164
|
-
|
|
165
|
-
| Option | Type | Required | Default | Description |
|
|
166
|
-
| -------------- | ----------------- | -------- | ---------------- | --------------------------------- |
|
|
167
|
-
| `proxyBaseUrl` | string | ✅ | - | Base URL of your API server |
|
|
168
|
-
| `mockDir` | string | ❌ | `'mock'` | Directory to store mock files |
|
|
169
|
-
| `apiPrefix` | string | ❌ | `'/api'` | API path prefix to intercept |
|
|
170
|
-
| `pathRewrite` | function | ❌ | `(path) => path` | Function to rewrite request paths |
|
|
171
|
-
| `inspector` | boolean \| object | ❌ | `false` | Enable visual mock inspector UI |
|
|
172
|
-
|
|
173
|
-
## Common Pitfalls
|
|
174
|
-
|
|
175
|
-
### ⚠️ Dual Proxy Configuration
|
|
249
|
+
## Production Mode
|
|
176
250
|
|
|
177
|
-
|
|
251
|
+
To use mock data in production builds:
|
|
178
252
|
|
|
179
|
-
|
|
180
|
-
```typescript
|
|
181
|
-
export default defineConfig({
|
|
182
|
-
plugins: [
|
|
183
|
-
automock({
|
|
184
|
-
proxyBaseUrl: "http://localhost:8888",
|
|
185
|
-
apiPrefix: "/api",
|
|
186
|
-
})
|
|
187
|
-
],
|
|
188
|
-
server: {
|
|
189
|
-
proxy: {
|
|
190
|
-
"/api": { // ❌ CONFLICTS with automock
|
|
191
|
-
target: "http://localhost:8888",
|
|
192
|
-
changeOrigin: true,
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
})
|
|
197
|
-
```
|
|
253
|
+
1. Enable `productionMock` and `bundleMockData`:
|
|
198
254
|
|
|
199
|
-
**✅ Correct:**
|
|
200
255
|
```typescript
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
})
|
|
207
|
-
],
|
|
208
|
-
// ✅ Remove server.proxy or use a different prefix
|
|
256
|
+
automock({
|
|
257
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
258
|
+
productionMock: true, // or 'auto'
|
|
259
|
+
bundleMockData: true, // default
|
|
260
|
+
bundleOutputPath: 'public/mock-data.json',
|
|
209
261
|
})
|
|
210
262
|
```
|
|
211
263
|
|
|
212
|
-
The plugin will
|
|
213
|
-
|
|
214
|
-
### Inspector Options
|
|
264
|
+
2. The plugin will generate `public/mock-data.json` at build time containing all mock data.
|
|
215
265
|
|
|
216
|
-
|
|
266
|
+
3. Initialize the client interceptor in your app (see [Client API Reference](#client-api-reference)).
|
|
217
267
|
|
|
218
|
-
|
|
219
|
-
| -------------- | ------- | ------------ | ---------------------------------- |
|
|
220
|
-
| `route` | string | `'/__mock/'` | Route path for the inspector UI |
|
|
221
|
-
| `enableToggle` | boolean | `true` | Allow toggling mock enable/disable |
|
|
268
|
+
4. The `productionMock: 'auto'` option automatically enables mock based on the environment.
|
|
222
269
|
|
|
223
|
-
## Mock Inspector
|
|
270
|
+
## Mock Inspector
|
|
224
271
|
|
|
225
|
-
|
|
272
|
+
The visual inspector provides a web UI to manage mock files:
|
|
226
273
|
|
|
227
|
-
```
|
|
274
|
+
```typescript
|
|
228
275
|
automock({
|
|
229
|
-
proxyBaseUrl:
|
|
230
|
-
inspector: true,
|
|
231
|
-
})
|
|
276
|
+
proxyBaseUrl: 'https://api.example.com',
|
|
277
|
+
inspector: true, // or { route: '/__mock/', enableToggle: true }
|
|
278
|
+
})
|
|
232
279
|
```
|
|
233
280
|
|
|
234
281
|
Then visit `http://localhost:5173/__mock/` to:
|
|
235
282
|
|
|
236
|
-
-
|
|
237
|
-
-
|
|
238
|
-
-
|
|
239
|
-
-
|
|
240
|
-
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
## How It Works
|
|
245
|
-
|
|
246
|
-
1. **Request Interception**: The plugin intercepts all requests matching the `apiPrefix`
|
|
247
|
-
2. **Mock Check**: Checks if a corresponding mock file exists
|
|
248
|
-
3. **Conditional Response**:
|
|
249
|
-
- If mock exists → Returns mock data
|
|
250
|
-
- If mock doesn't exist → Proxies to real API and saves response as mock
|
|
251
|
-
4. **Auto-Generation**: Real API responses are automatically saved as mock files
|
|
252
|
-
5. **Hot Reloading**: Changes to mock files are automatically detected and reloaded
|
|
253
|
-
6. **Visual Inspector**: Manage and edit mocks through the web UI
|
|
283
|
+
- **Browse** all mock files organized by URL
|
|
284
|
+
- **Toggle** mock enable/disable status
|
|
285
|
+
- **Adjust** response delay and status codes
|
|
286
|
+
- **Edit** JSON response data directly
|
|
287
|
+
- **Create** new mock files
|
|
288
|
+
- **Delete** existing mock files
|
|
289
|
+
- **Batch update** multiple mocks at once
|
|
254
290
|
|
|
255
291
|
## Mock File Structure
|
|
256
292
|
|
|
@@ -267,7 +303,7 @@ mock/
|
|
|
267
303
|
│ └── post.js # POST /api/items
|
|
268
304
|
```
|
|
269
305
|
|
|
270
|
-
Each mock file exports an object
|
|
306
|
+
Each mock file exports an object:
|
|
271
307
|
|
|
272
308
|
```javascript
|
|
273
309
|
/**
|
|
@@ -275,9 +311,8 @@ Each mock file exports an object with this structure:
|
|
|
275
311
|
* Generated at 2025-01-11T10:30:00.000Z
|
|
276
312
|
*/
|
|
277
313
|
export default {
|
|
278
|
-
enable: false,
|
|
314
|
+
enable: false, // Whether to use this mock
|
|
279
315
|
data: {
|
|
280
|
-
// Response data
|
|
281
316
|
code: 0,
|
|
282
317
|
message: "success",
|
|
283
318
|
data: [
|
|
@@ -285,55 +320,77 @@ export default {
|
|
|
285
320
|
{ id: 2, name: "User 2" },
|
|
286
321
|
],
|
|
287
322
|
},
|
|
288
|
-
delay: 0,
|
|
323
|
+
delay: 0, // Artificial delay in milliseconds
|
|
289
324
|
status: 200, // HTTP status code
|
|
290
|
-
}
|
|
325
|
+
}
|
|
291
326
|
```
|
|
292
327
|
|
|
293
|
-
|
|
328
|
+
### Dynamic Mock Data
|
|
294
329
|
|
|
295
|
-
|
|
330
|
+
```javascript
|
|
331
|
+
export default {
|
|
332
|
+
enable: true,
|
|
333
|
+
data: () => ({
|
|
334
|
+
timestamp: new Date().toISOString(),
|
|
335
|
+
randomId: Math.floor(Math.random() * 1000),
|
|
336
|
+
}),
|
|
337
|
+
}
|
|
338
|
+
```
|
|
296
339
|
|
|
297
|
-
|
|
298
|
-
pnpm run example
|
|
299
|
-
```
|
|
340
|
+
## Common Pitfalls
|
|
300
341
|
|
|
301
|
-
|
|
342
|
+
### Dual Proxy Configuration
|
|
302
343
|
|
|
303
|
-
|
|
344
|
+
**Do NOT** configure both Vite's `server.proxy` and automock's `proxyBaseUrl` for the same API prefix:
|
|
304
345
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
346
|
+
```typescript
|
|
347
|
+
// ❌ Wrong - will cause request conflicts
|
|
348
|
+
export default defineConfig({
|
|
349
|
+
plugins: [
|
|
350
|
+
automock({ proxyBaseUrl: 'http://localhost:8888', apiPrefix: '/api' })
|
|
351
|
+
],
|
|
352
|
+
server: {
|
|
353
|
+
proxy: {
|
|
354
|
+
'/api': { target: 'http://localhost:8888', changeOrigin: true } // CONFLICTS
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
// ✅ Correct - use automock for /api, remove server.proxy
|
|
360
|
+
export default defineConfig({
|
|
361
|
+
plugins: [
|
|
362
|
+
automock({ proxyBaseUrl: 'http://localhost:8888', apiPrefix: '/api' })
|
|
363
|
+
]
|
|
364
|
+
})
|
|
365
|
+
```
|
|
308
366
|
|
|
309
|
-
|
|
310
|
-
import { automock } from "vite-plugin-automock";
|
|
367
|
+
The plugin will automatically warn you if a conflicting proxy is detected.
|
|
311
368
|
|
|
312
|
-
|
|
313
|
-
plugins: [
|
|
314
|
-
automock({
|
|
315
|
-
proxyBaseUrl: "http://localhost:8888"
|
|
316
|
-
})
|
|
317
|
-
]
|
|
318
|
-
};
|
|
319
|
-
```
|
|
369
|
+
## How It Works
|
|
320
370
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
-
|
|
325
|
-
-
|
|
371
|
+
1. **Request Interception**: The plugin intercepts all requests matching `apiPrefix`
|
|
372
|
+
2. **Mock Check**: Checks if a corresponding mock file exists and is enabled
|
|
373
|
+
3. **Conditional Response**:
|
|
374
|
+
- Mock exists and enabled -> Returns mock data
|
|
375
|
+
- Mock exists but disabled -> Skips to proxy or next middleware
|
|
376
|
+
- Mock doesn't exist -> Proxies to real API (if `proxy: true`)
|
|
377
|
+
4. **Auto-Capture**: Real API responses are automatically saved as mock files (if `capture: true`)
|
|
378
|
+
5. **Hot Reloading**: Changes to mock files are automatically detected and reloaded
|
|
379
|
+
6. **Bundle**: Mock data is bundled into JSON for production use
|
|
326
380
|
|
|
327
381
|
## Comparison with Traditional Mock Plugins
|
|
328
382
|
|
|
329
|
-
| Feature
|
|
330
|
-
|
|
|
331
|
-
| Auto backfill
|
|
332
|
-
| Legacy project support |
|
|
333
|
-
| Manual mock files
|
|
334
|
-
| Config complexity
|
|
335
|
-
| Zero setup
|
|
336
|
-
| Real API integration
|
|
383
|
+
| Feature | Traditional Mock Plugins | vite-plugin-automock |
|
|
384
|
+
| ------- | ----------------------- | -------------------- |
|
|
385
|
+
| Auto backfill | - | Yes |
|
|
386
|
+
| Legacy project support | - | Yes |
|
|
387
|
+
| Manual mock files | Yes | Yes |
|
|
388
|
+
| Config complexity | High | Very low |
|
|
389
|
+
| Zero setup | - | Yes |
|
|
390
|
+
| Real API integration | - | Yes |
|
|
391
|
+
| Fine-grained control | - | Yes |
|
|
392
|
+
| Visual inspector | - | Yes |
|
|
393
|
+
| Production mock | - | Yes |
|
|
337
394
|
|
|
338
395
|
## When to Use
|
|
339
396
|
|
|
@@ -343,45 +400,6 @@ export default {
|
|
|
343
400
|
- **Testing**: Consistent test data without external dependencies
|
|
344
401
|
- **Demo/Presentation**: Reliable demo data that doesn't change
|
|
345
402
|
|
|
346
|
-
## Advanced Usage
|
|
347
|
-
|
|
348
|
-
### Custom Path Rewriting
|
|
349
|
-
|
|
350
|
-
```javascript
|
|
351
|
-
automock({
|
|
352
|
-
proxyBaseUrl: "http://api.example.com",
|
|
353
|
-
pathRewrite: (path) => {
|
|
354
|
-
// Remove /api prefix when proxying
|
|
355
|
-
return path.replace(/^\/api/, "");
|
|
356
|
-
},
|
|
357
|
-
});
|
|
358
|
-
```
|
|
359
|
-
|
|
360
|
-
### Conditional Mock Enabling
|
|
361
|
-
|
|
362
|
-
```javascript
|
|
363
|
-
// In your mock file
|
|
364
|
-
export default {
|
|
365
|
-
enable: process.env.NODE_ENV === "development",
|
|
366
|
-
data: {
|
|
367
|
-
/* mock data */
|
|
368
|
-
},
|
|
369
|
-
};
|
|
370
|
-
```
|
|
371
|
-
|
|
372
|
-
### Dynamic Mock Data
|
|
373
|
-
|
|
374
|
-
```javascript
|
|
375
|
-
// In your mock file
|
|
376
|
-
export default {
|
|
377
|
-
enable: true,
|
|
378
|
-
data: () => ({
|
|
379
|
-
timestamp: new Date().toISOString(),
|
|
380
|
-
randomId: Math.floor(Math.random() * 1000),
|
|
381
|
-
}),
|
|
382
|
-
};
|
|
383
|
-
```
|
|
384
|
-
|
|
385
403
|
## Contributing
|
|
386
404
|
|
|
387
405
|
We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
|
package/dist/index.d.mts
CHANGED
|
@@ -13,6 +13,12 @@ interface AutomockPluginOptions {
|
|
|
13
13
|
proxyBaseUrl?: string;
|
|
14
14
|
inspector?: boolean | InspectorOptions;
|
|
15
15
|
productionMock?: boolean | 'auto';
|
|
16
|
+
/** Global switch, default true. When false, middleware passes through all requests. */
|
|
17
|
+
enabled?: boolean;
|
|
18
|
+
/** Whether to proxy unmatched requests to proxyBaseUrl, default true. */
|
|
19
|
+
proxy?: boolean;
|
|
20
|
+
/** Whether to capture and save new mock files from proxy responses, default true. */
|
|
21
|
+
capture?: boolean;
|
|
16
22
|
}
|
|
17
23
|
|
|
18
24
|
interface MockFileConfig {
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,12 @@ interface AutomockPluginOptions {
|
|
|
13
13
|
proxyBaseUrl?: string;
|
|
14
14
|
inspector?: boolean | InspectorOptions;
|
|
15
15
|
productionMock?: boolean | 'auto';
|
|
16
|
+
/** Global switch, default true. When false, middleware passes through all requests. */
|
|
17
|
+
enabled?: boolean;
|
|
18
|
+
/** Whether to proxy unmatched requests to proxyBaseUrl, default true. */
|
|
19
|
+
proxy?: boolean;
|
|
20
|
+
/** Whether to capture and save new mock files from proxy responses, default true. */
|
|
21
|
+
capture?: boolean;
|
|
16
22
|
}
|
|
17
23
|
|
|
18
24
|
interface MockFileConfig {
|
package/dist/index.js
CHANGED
|
@@ -859,7 +859,10 @@ function automock(options) {
|
|
|
859
859
|
apiPrefix = "/api",
|
|
860
860
|
pathRewrite = (p) => p,
|
|
861
861
|
proxyBaseUrl,
|
|
862
|
-
inspector = false
|
|
862
|
+
inspector = false,
|
|
863
|
+
enabled = true,
|
|
864
|
+
proxy: proxyEnabled = true,
|
|
865
|
+
capture: captureEnabled = true
|
|
863
866
|
} = options;
|
|
864
867
|
const mockDir = resolveAbsolutePath(configMockDir);
|
|
865
868
|
if (!import_fs_extra3.default.existsSync(mockDir)) {
|
|
@@ -937,6 +940,7 @@ function automock(options) {
|
|
|
937
940
|
}
|
|
938
941
|
server.middlewares.use(
|
|
939
942
|
async (req, res, next) => {
|
|
943
|
+
if (!enabled) return next();
|
|
940
944
|
if (inspectorHandler && req.url) {
|
|
941
945
|
const handled = await inspectorHandler(req, res);
|
|
942
946
|
if (handled) return;
|
|
@@ -961,12 +965,12 @@ function automock(options) {
|
|
|
961
965
|
} catch (error) {
|
|
962
966
|
console.error("[automock] Failed to load mock file:", error);
|
|
963
967
|
}
|
|
964
|
-
if (!proxyBaseUrl) return next();
|
|
968
|
+
if (!proxyBaseUrl || !proxyEnabled) return next();
|
|
965
969
|
try {
|
|
966
970
|
proxyAndCapture(req, res, {
|
|
967
971
|
proxyBaseUrl,
|
|
968
972
|
pathRewrite,
|
|
969
|
-
shouldSave: !mockFileMap.has(key),
|
|
973
|
+
shouldSave: captureEnabled && !mockFileMap.has(key),
|
|
970
974
|
method,
|
|
971
975
|
pathname,
|
|
972
976
|
mockDir,
|