vite-plugin-file-mock v0.2.5
vite-plugin-file-mock 
File system based local mock plugin for vite
English | 中文
Table of Contents
Usage
yarn add vite-plugin-file-mock -D
# or
npm i vite-plugin-file-mock -D// vite.config.js
import mockPlugin from 'vite-plugin-file-mock'
export default {
plugins: [
mockPlugin(),
]
}interface MockPluginOptions {
dir?: string;
enable?: boolean;
refreshOnSave?: boolean;
noRefreshUrlList?: Array<string | RegExp>;
}See example for more detail
Options
dir
- Type:
string - Default:
mock
The mock file folder relative to vite root, use mock by default
enable
- Type:
boolean - Default:
true
Enable mock plugin or not.
This plugin load only in serve
refreshOnSave
- Type:
boolean - Default:
true
When mock file change, the browser will be refresh
noRefreshUrlList
- Type:
Array<string | RegExp> - Default:
[]
When some file change, you dont want to refresh the browser, you can use this.
Overview
By default, the plugin will select all .js and .ts(and .mjs or .cjs, .mts and .cts dont support yet) files in the vite root mock folder to generate mock data, the api url is just the file path
mock/
├── api/
│ ├── home.js
│ ├── user.jsThe above directory structure will generate two apis /api/home and /api/user
// home.js
module.exports = {
result: 1,
}fetch('/api/home')
.then(response => response.json())
.then(data => console.log(data)); // { result: 1}Customize Content
Sometimes we need to customize the returned content, we can return a function to dynamic generate mock data.
Or you can use response to generate statusCode, header, responseData etc.
If response.end is not called in the function, the return value of the function will be the value returned by the final response
// user.js module.exports = (request, response) => { if (request.method === 'GET') { return { result: 1, method: request.method, } } else if (request.method === 'POST') { return { result: 2, method: request.method, } } else { response.statusCode = 500; response.end(JSON.stringify({ result: 3, method: request.method, })); } }
TypeScript And ESM Support
This plugin can support .js and .ts both, .js file can be commonjs or esm
// home.js commonjs
module.exports = {
result: 1,
};// home.js esm
export default {
result: 1,
};// home.ts
export default () => {
return {
result: 1
}
}Async Function
mock can also support async function, so that you can do more thing;
async function delay(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
});
}
// return data after 5 second
export default async () => {
const data = {
result: 1,
};
await delay(5000);
return data;
};Ignore Interface
Sometimes we dont want the data from local, you can do this in two ways
- comment the file
// home.js
// export default {
// result: 1,
// };- return undefined
// home.js
export default {
result: 1,
} && undefined;