vite-plugin-mock-dev-server
Vite Plugin for API mock dev server.
English | 简体中文
Feature
- ⚡️ light weight,flexible,fast
- 🧲 Non - injection, no intrusion to client code
- 💡 ESModule/commonjs
- 🦾 Typescript
- 🏷 Support json / json5
- 📦 Auto import mock file
- 🎨 Support any lib,like
mockjs
,or not use it. - 📥 Path rules match and request parameters match
- ⚙️ Support Enabled/Disabled any one of api mock
- 🔥 HMR
- ⚖️ Use
server.proxy
- 🍕 Support
viteConfig.define
in mock file - 📤 Support
multipart
content-type,mock upload file.
Documentation
See the documentation to learn more.
Usage
Install
npm i -D vite-plugin-mock-dev-server
yarn add vite-plugin-mock-dev-server
pnpm add -D vite-plugin-mock-dev-server
Configuration
vite.config.ts
import { defineConfig } from 'vite'
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
export default defineConfig({
plugins: [
mockDevServerPlugin(),
],
define: {},
server: {
proxy: {
'^/api': {
target: 'http://example.com'
}
}
}
})
The plugin reads the configuration for server.proxy
and enables mock matching only for urls where the proxy is set.
The plugin also reads the define
configuration and supports direct use in mock files.
In a general case, we only need to mock the url with the proxy so that we can proxy and mock through the http service provided by vite
Edit Mock File
By default, write mock data in the mock
directory of your project root:
mock/api.mock.ts
:
import { defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/test',
body: {
a: 1,
b: 2,
}
})
Methods
mockDevServerPlugin(options)
vite plugin
vite.config.ts
import { defineConfig } from 'vite'
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
export default defineConfig({
plugins: [
mockDevServerPlugin(),
]
})
options
-
option.include
Configure to read mock files, which can be a directory, glob, or array
Default: ['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']
(relative for process.cwd()
)
-
options.exclude
When you configure the mock files to be read, the files you want to exclude can be a directory, glob, or array
Default:
[
'**/node_modules/**',
'**/test/**',
'src/**',
'**/.vscode/**',
'**/.git/**',
'**/dist/**'
]
-
options.formidableOptions
Configure to formidable
,see formidable options
Default: {}
example: Configure to file upload dir
MockDevServerPlugin({
formidableOptions: {
uploadDir: path.join(process.cwd(), 'uploads'),
}
})
defineMock(config)
Mock Type Helper
import { defineMock } from 'vite-plugin-mock-dev-server'
export default defineMock({
url: '/api/test',
body: {}
})
Mock Configuration
export default defineMock({
url: '/api/test',
method: ['GET', 'POST'],
enable: true,
delay: 1000,
status: 200,
statusText: 'OK',
validator: {
headers: {},
body: {},
query: {},
params: {},
},
headers: {
'Content-Type': 'application/json'
},
body: {},
response(req, res, next) {
res.end()
}
})
Tips:
If you write mock files using json/json5,
the 'response' method is not supported,
as is the function form that uses other fields.
mock/**/*.mock.{ts,js,mjs,cjs,json,json5}
See more examples: example
Example 1:
Match /api/test
,And returns a response body content with empty data
export default defineMock({
url: '/api/test',
})
Example 2:
Match /api/test
,And returns a static content data
export default defineMock({
url: '/api/test',
body: {
a: 1
}
})
Example 3:
Only Support GET
Method
export default defineMock({
url: '/api/test',
method: 'GET'
})
Example 4:
In the response header, add a custom header
export default defineMock({
url: '/api/test',
headers: {
'X-Custom': '12345678'
}
})
export default defineMock({
url: '/api/test',
headers({ query, body, params, headers }) {
return {
'X-Custom': query.custom
}
}
})
Example 5:
Define multiple mock requests for the same url and match valid rules with validators
export default defineMock([
{
url: '/api/test',
validator: {
query: {
a: 1
}
},
body: {
message: 'query.a === 1'
}
},
{
url: '/api/test',
validator: {
query: {
a: 2
}
},
body: {
message: 'query.a === 2'
}
}
])
Example 6:
Response Delay
export default defineMock({
url: '/api/test',
delay: 6000,
})
Example 7:
The interface request failed
export default defineMock({
url: '/api/test',
status: 504,
statusText: 'Bad Gateway'
})
Example 8:
Use mockjs
:
import Mock from 'mockjs'
export default defineMock({
url: '/api/test',
body: Mock.mock({
'list|1-10': [{
'id|+1': 1
}]
})
})
You need installed mockjs
Example 9:
Use response
to customize the response
export default defineMock({
url: '/api/test',
response(req, res, next) {
const { query, body, params, headers } = req
console.log(query, body, params, headers)
res.status = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({
query,
body,
params,
}))
}
})
Example 10:
Use json / json5
{
"url": "/api/test",
"body": {
"a": 1
}
}
Example 11:
multipart, upload file.
use formidable
to supported.
<form action="/api/upload" method="post" enctype="multipart/form-data">
<p>
<span>file: </span>
<input type="file" name="files" multiple />
</p>
<p>
<span>name:</span>
<input type="text" name="name" value="mark">
</p>
<p>
<input type="submit" value="submit">
</p>
</form>
fields files
mapping to formidable.File
export default defineMock({
url: '/api/upload',
method: 'POST',
body(req) {
const body = req.body
return {
name: body.name,
files: body.files.map((file: any) => file.originalFilename),
}
},
})
Archives
awesome-vite
LICENSE
GPL-3.0