Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

vite-plugin-mock

anncwb59.1kMIT3.0.2TypeScript support: included

A mock plugin for vite

vite, mock, hmr

readme

vite-plugin-mock

English | 中文

npm node

Provide local and prod mocks for vite.

A mock plugin for vite, developed based on mockjs. And support the local environment and production environment at the same time. Connect service middleware is used locally, mockjs is used online

Install (yarn or npm)

node version: >=12.0.0

vite version: >=2.0.0

yarn add mockjs
# or
npm i  mockjs -S
# or
pnpm add mockjs

and

yarn add vite-plugin-mock -D
# or
npm i vite-plugin-mock -D
# or
pnpm add vite-plugin-mock -D

Example

Run Example


# ts example
cd ./examples/ts-examples

yarn install

yarn serve

# js example

cd ./examples/js-examples

yarn install

yarn serve

Usage

Development environment

The development environment is implemented using Connect middleware。

Different from the production environment, you can view the network request record in the Google Chrome console

  • Config plugin in vite.config.ts
import { UserConfigExport, ConfigEnv } from 'vite'

import { viteMockServe } from 'vite-plugin-mock'
import vue from '@vitejs/plugin-vue'

export default ({ command }: ConfigEnv): UserConfigExport => {
  return {
    plugins: [
      vue(),
      viteMockServe({
        // default
        mockPath: 'mock',
        enable: true,
      }),
    ],
  }
}
  • viteMockServe Options
{
    mockPath?: string;
    ignore?: RegExp | ((fileName: string) => boolean);
    watchFiles?: boolean;
    enable?: boolean;
    ignoreFiles?: string[];
    configPath?: string;
}

Options

mockPath

type: string

default: 'mock'

Set the folder where the mock .ts file is stored

If watchFiles:true, the file changes in the folder will be monitored. And synchronize to the request result in real time

If configPath has a value, it is invalid

ignore

type: RegExp | ((fileName: string) => boolean);

default: undefined

When automatically reading analog .ts files, ignore files in the specified format

watchFiles

type: boolean

default: true

Set whether to monitor changes in mock .ts files

enable

type: boolean

default: true

Whether to enable the mock function

configPath

type: string

default: vite.mock.config.ts

Set the data entry that the mock reads. When the file exists and is located in the project root directory, the file will be read and used first. The configuration file returns an array

logger

type: boolean

default: true

Whether to display the request log on the console

Mock file example

/path/mock

// test.ts

import { MockMethod, MockConfig } from 'vite-plugin-mock'
export default [
  {
    url: '/api/get',
    method: 'get',
    response: ({ query }) => {
      return {
        code: 0,
        data: {
          name: 'vben',
        },
      }
    },
  },
  {
    url: '/api/post',
    method: 'post',
    timeout: 2000,
    response: {
      code: 0,
      data: {
        name: 'vben',
      },
    },
  },
  {
    url: '/api/text',
    method: 'post',
    rawResponse: async (req, res) => {
      let reqbody = ''
      await new Promise((resolve) => {
        req.on('data', (chunk) => {
          reqbody += chunk
        })
        req.on('end', () => resolve(undefined))
      })
      res.setHeader('Content-Type', 'text/plain')
      res.statusCode = 200
      res.end(`hello, ${reqbody}`)
    },
  },
] as MockMethod[]

export default function (config: MockConfig) {
  return [
    {
      url: '/api/text',
      method: 'post',
      rawResponse: async (req, res) => {
        let reqbody = ''
        await new Promise((resolve) => {
          req.on('data', (chunk) => {
            reqbody += chunk
          })
          req.on('end', () => resolve(undefined))
        })
        res.setHeader('Content-Type', 'text/plain')
        res.statusCode = 200
        res.end(`hello, ${reqbody}`)
      },
    },
  ]
}

MockMethod

{
  // request url
  url: string;
  // request method
  method?: MethodType;
  // Request time in milliseconds
  timeout?: number;
  // default: 200
  statusCode?:number;
  // response data (JSON)
  response?: ((opt: { [key: string]: string; body: Record<string,any>; query:  Record<string,any>, headers: Record<string, any>; }) => any) | any;
  // response (non-JSON)
  rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
}

Create the mockProdServer.ts file

//  mockProdServer.ts

import { createProdMockServer } from 'vite-plugin-mock/client'

// Import your mock .ts files one by one
// If you use vite.mock.config.ts, just import the file directly
// You can use the import.meta.glob function to import all
import testModule from '../mock/test'

export function setupProdMockServer() {
  createProdMockServer([...testModule])
}

Config vite-plugin-mock

import { viteMockServe } from 'vite-plugin-mock'

import { UserConfigExport, ConfigEnv } from 'vite'

export default ({ command }: ConfigEnv): UserConfigExport => {
  return {
    plugins: [
      viteMockServe({
        mockPath: 'mock',
        // According to the project configuration. Can be configured in the .env file
        enable: true,
      }),
    ],
  }
}

Sample project

Vben Admin

Note

  • The node module cannot be used in the mock .ts file, otherwise the production environment will fail
  • Mock is used in the production environment, which is only suitable for some test environments. Do not open it in the formal environment to avoid unnecessary errors. At the same time, in the production environment, it may affect normal Ajax requests, such as file upload failure, etc.

License

MIT

changelog

[3.0.0]

Breaking Change

  • Remove the localEnabled and prodEnabled configuration and use the enable configuration instead, no longer distinguishing the environment
  • Remove the injectFileinjectCode and supportTs configuration
  • Minimum requirement NodeJs 16
  • Production Environment Syntax Changes
// vite-plugin-mock/es/createProdMockServer => vite-plugin-mock/client
import { createProdMockServer } from 'vite-plugin-mock/client'
import roleMock from '../mock/dep/role'
// functional form
import userMockFn from '../mock/user'

export async function setupProdMockServer() {
  const mockModules = [...roleMock, ...userMockFn()]
  createProdMockServer(mockModules)
}

Features

  • Upgrade all dependencies to latest
  • support vite4 and rollup3
  • The function module supports returning a function
import type { MockConfig } from 'vite-plugin-mock'

export default (config?: MockConfig) => {
  return [
    {
      url: '/api/createUser',
      method: 'post',
      response: ({ body, query }) => {
        console.log('body>>>>>>>>', body)
        console.log('query>>>>>>>>', query)

        return {
          code: 0,
          message: 'ok',
          data: { a: 21, 'import.meta.url': import.meta.url },
        }
      },
    },
  ]
}

2.9.8 (2023-04-17)

Bug Fixes

Features

  • prod: response 在 prod 模式下入参对象加上 url (#83) (cd0b86f)
  • server: add this for response, rawResponse function (#43) (2f4d6d2)

2.9.8 (2023-04-16)

Bug Fixes

Features

  • prod: response 在 prod 模式下入参对象加上 url (#83) (cd0b86f)
  • server: add this for response, rawResponse function (#43) (2f4d6d2)

2.9.6 (2021-08-23)

Bug Fixes

Features

  • remove supportTs, change to automatic judgment (4625e59)
  • response return url (#27) (de9ed27)
  • server: add this for response, rawResponse function (#43) (2f4d6d2)

Reverts

2.9.5 (2021-08-23)

Bug Fixes

Features

  • remove supportTs, change to automatic judgment (4625e59)
  • response return url (#27) (de9ed27)
  • server: add this for response, rawResponse function (#43) (2f4d6d2)

Reverts

2.9.4 (2021-08-01)

Bug Fixes

2.9.3 (2021-07-18)

Bug Fixes

  • ensure that the post with parameters are matched,fix #29 (4cb55f8)
  • fix js parsing error (1dbee45)
  • improve path matching logic, fix #25 (5079e4b)
  • loss request headers in PROD mode (#23) (76302df), closes #15
  • make sure ignore matches the file correctly (b612a09)
  • support node12 (fdfed60)

Features

  • remove supportTs, change to automatic judgment (4625e59)
  • response return url (#27) (de9ed27)

Reverts

2.9.2 (2021-07-18)

Bug Fixes

  • ensure file changes take effect,fix #36 (353aa9d)
  • ensure that the post with parameters are matched,fix #29 (4cb55f8)
  • fix js parsing error (1dbee45)
  • improve path matching logic, fix #25 (5079e4b)
  • loss request headers in PROD mode (#23) (76302df), closes #15
  • make sure ignore matches the file correctly (b612a09)
  • support node12 (fdfed60)

Features

  • remove supportTs, change to automatic judgment (4625e59)
  • response return url (#27) (de9ed27)

Reverts

2.9.1 (2021-07-06)

Bug Fixes

  • ensure that the post with parameters are matched,fix #29 (4cb55f8)
  • fix js parsing error (d2746b6)
  • improve path matching logic, fix #25 (5079e4b)
  • loss request headers in PROD mode (#23) (76302df), closes #15
  • make sure ignore matches the file correctly (b612a09)
  • support node12 (fdfed60)

Features

  • remove supportTs, change to automatic judgment (4625e59)
  • response return url (#27) (de9ed27)

Reverts

2.9.0 (2021-07-05)

Bug Fixes

  • ensure that the post with parameters are matched,fix #29 (4cb55f8)
  • improve path matching logic, fix #25 (5079e4b)
  • loss request headers in PROD mode (#23) (76302df), closes #15
  • make sure ignore matches the file correctly (b612a09)
  • support node12 (fdfed60)

Features

  • remove supportTs, change to automatic judgment (4625e59)
  • response return url (#27) (de9ed27)

Reverts

2.8.0 (2021-06-16)

Bug Fixes

  • ensure that the post with parameters are matched,fix #29 (bfed256)
  • improve path matching logic, fix #25 (5079e4b)
  • loss request headers in PROD mode (#23) (76302df), closes #15
  • make sure ignore matches the file correctly (b612a09)
  • support node12 (fdfed60)

Features

  • remove supportTs, change to automatic judgment (a341c7d)
  • response return url (#27) (de9ed27)

Reverts

2.7.2 (2021-06-10)

Bug Fixes

  • improve path matching logic, fix #25 (5079e4b)
  • loss request headers in PROD mode (#23) (76302df), closes #15
  • make sure ignore matches the file correctly (b612a09)
  • support node12 (fdfed60)

Features

Reverts

2.7.1 (2021-06-09)

Bug Fixes

Features

Reverts

2.6.0 (2021-05-29)

Bug Fixes

Reverts

2.5.0 (2021-04-06)

Bug Fixes

  • production xhr (6c94783)
  • eslint warn: fix some warn (b44c13b)
  • empty TS file in mock folder is error (669b804)

Features

  • add rawResponse option to MockMethod (#17) (24775f9), closes #16

Performance Improvements

2.4.1 (2021-03-30)

Bug Fixes

  • empty TS file in mock folder is error (669b804)

Performance Improvements

2.4.0 (2021-03-25)

Features

2.2.4 (2021-03-10)

Features

2.2.3 (2021-03-10)

Bug Fixes

  • ensure that the URLs of different request methods cannot match close #6 (361a3eb)

Features

2.2.1 (2021-03-09)

Features

2.2.0 (2021-03-02)

Features

2.1.5 (2021-02-23)

Bug Fixes

Features

Performance Improvements

2.0.0-beta.1 (2021-01-03)

Bug Fixes

  • Fix local development post request proxy to https (7965604)
  • remove unnecessary and wrong usage of "try catch" (815abde)

Features

1.0.2 (2020-09-14)

Features

1.0.1 (2020-09-14)

Features

  • add supportTs options,Support es6 and commonjs modules in .js folder (37f83f5)

Performance Improvements

  • Replace typescript plug-in with a faster esbuild plug-in (58ad7cd)