4.0.6 • Published 3 months ago

vite-plugin-mock-data v4.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

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

4.0.6

3 months ago

4.0.5

4 months ago

4.0.4

4 months ago

4.0.2

5 months ago

4.0.1

5 months ago

4.0.0

8 months ago

1.0.0

2 years ago