Skip to content

Latest commit

 

History

History

vite-plugin-mock-data

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

vite-plugin-mock-data

npm package

Provides a simple way to mock data. Vite >= 3.1

NPM version NPM Downloads

Installation

npm install vite-plugin-mock-data --save-dev

Options

  • cwd - Default: process.cwd().
  • isAfter - If true, these mock routes is matched after internal middlewares are installed.
  • mockAssetsDir - Specify the directory to define mock assets.
  • mockRouterOptions - Initial options of find-my-way
  • mockRoutes - Initial list of mock routes that should be added to the dev server.
  • mockRoutesDir - Specify the directory to define mock routes that should be added to the dev server.

Usage

Specify the directory to define mock assets

import { defineConfig } from 'vite';
import mockData from 'vite-plugin-mock-data';

export default defineConfig({
  plugins: [
    mockData({
      mockAssetsDir: './mockAssets'
    })
  ]
});
.
├── mockAssets
│   ├── test.zip
│   └── test.json
fetch('/test.json')
  .then(res => res.json())
  .then((json) => {
    console.log(json);
  });
<a class="download" href="./test.zip">Download</a>

add mock routes to the dev server

import { defineConfig } from 'vite';
import mockData from 'vite-plugin-mock-data';

export default defineConfig({
  plugins: [
    mockData({
      mockRoutes: {
        '/hello': 'hello',
        '/hello2'(req, res) {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'text/html');
          res.end('hello2');
        },
        '/hello3': {
          handler(req, res) {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.end('hello3');
          }
        },
        '/json': {
          handler: { hello: 1 }
        },
        '/package.json': {
          file: './package.json'
        }
      }
    })
  ]
});
fetch('/package.json')
  .then(res => res.json())
  .then((json) => {
    console.log(json);
  });

Specify the directory to add mock routes to the dev server

import { defineConfig } from 'vite';
import mockData from 'vite-plugin-mock-data';

export default defineConfig({
  plugins: [
    mockData({
      mockRoutesDir: './mock'
    })
  ]
});
.
├── mock
│   └── test.js
module.exports = {
  '/hello': 'hello',
  '/hello2'(req, res) {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('hello2');
  },
  '/hello3': {
    handler(req, res) {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/html');
      res.end('hello3');
    }
  },
  '/json': {
    handler: { hello: 1 }
  },
  '/package.json': {
    file: './package.json'
  }
};
fetch('/package.json')
  .then(res => res.json())
  .then((json) => {
    console.log(json);
  });

Examples