Socket
Socket
Sign inDemoInstall

@meadmin-cn/vite-plugin-mock

Package Overview
Dependencies
221
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @meadmin-cn/vite-plugin-mock

A mock plugin for vite forked from vbenjs/vite-plugin-mock


Version published
Weekly downloads
6
Maintainers
1
Created
Weekly downloads
 

Changelog

Source

2.9.8 (2022-09-23)

Bug Fixes

  • can't update in real time, fix #40 (f25c6ac)
  • correct sourcemap (2140987)
  • dev sourcemap (5834b4f)
  • empty TS file in mock folder is error (669b804)
  • ensure that the post with parameters are matched,fix #29 (4cb55f8)
  • ensure that the URLs of different request methods cannot match close #6 (efe943d)
  • error handle, fix #39 (874318c)
  • eslint warn: fix some warn (b44c13b)
  • fix js parsing error (1dbee45)
  • Fix local development post request proxy to https (7965604)
  • fix node version (#38) (f91dea1)
  • fix post proxy error (d3ae41e)
  • 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)
  • prod 模式下加上 url (f420ed1)
  • production xhr (6c94783)
  • remove unnecessary and wrong usage of "try catch" (815abde)
  • support node12 (fdfed60)
  • typo, close #42 (5b4e946)

Features

  • add examples (2c5a86b)
  • add logger option (66a75ab)
  • add rawResponse option to MockMethod (#17) (24775f9), closes #16
  • add request time (ccbb14a)
  • add supportTs options,Support es6 and commonjs modules in .js folder (37f83f5)
  • prod: response 在 prod 模式下入参对象加上 url (#83) (cd0b86f)
  • remove supportTs, change to automatic judgment (4625e59)
  • response return headers, close #10 (eff3794)
  • response return url (#27) (de9ed27)
  • server: add this for response, rawResponse function (#43) (2f4d6d2)
  • support post restful close #7 (70b51e8)
  • support restful api close #4 (236393e)
  • support sourcemap (8c3cd9d)

Performance Improvements

  • imporve request log (f9353fd)
  • perf code (98b9dbc)
  • Replace typescript plug-in with a faster esbuild plug-in (58ad7cd)

Reverts

Readme

Source

vite-plugin-mock

English | 中文

npm node

The package forked from [vbenjs/vite - plugin - mock] (https://github.com/vbenjs/vite-plugin-mock), because vbenjs/vite - plugin - mock stop maintenance, I needed to use its functionality again, so I copied 'vbenjs/vite-plugin-mock' to fix the bug and republish it

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
yarn add @meadmin-cn/vite-plugin-mock -D
# or
npm i @meadmin-cn/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 '@meadmin-cn/vite-plugin-mock'
import vue from '@vitejs/plugin-vue'

export default ({ command }: ConfigEnv): UserConfigExport => {
  return {
    plugins: [
      vue(),
      viteMockServe({
        // default
        mockPath: 'mock',
        localEnabled: command === 'serve',
      }),
    ],
  }
}
  • viteMockServe Options
{
    mockPath?: string;
    supportTs?: boolean;
    ignore?: RegExp | ((fileName: string) => boolean);
    watchFiles?: boolean;
    localEnabled?: boolean;
    ignoreFiles?: string[];
    configPath?: string;
    prodEnabled?: boolean;
    injectFile?: string;
    injectCode?: 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

supportTs

type: boolean

default: true

After opening, the ts file module can be read. Note that you will not be able to monitor .js files after opening.

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

localEnabled

type: boolean

default: command === 'serve'

Set whether to enable the local mock .ts file, do not open it in the production environment

prodEnabled

type: boolean

default: command !=='serve'

Set whether to enable mock function for packaging

injectCode

type: string

default:''

If the mock function is enabled in the production environment, that is, prodEnabled=true, the code will be injected into the bottom of the file corresponding to injectFile. The default is main.{ts,js}

The advantage of this is that you can dynamically control whether mock is enabled in the production environment and mock.js will not be packaged when it is not enabled.

If the code is written directly in main.ts, no matter whether it is turned on or not, the final package will include mock.js

injectFile

type: string

default: path.resolve(process.cwd(),'src/main.{ts,js}')

The file injected by injectCode code, the default is src/main.{ts,js} in the project root directory

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 } from '@meadmin-cn/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[]

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 '@meadmin-cn/vite-plugin-mock/es/createProdMockServer'

// 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 '@meadmin-cn/vite-plugin-mock'

import { UserConfigExport, ConfigEnv } from 'vite'

export default ({ command }: ConfigEnv): UserConfigExport => {
  // According to the project configuration. Can be configured in the .env file
  let prodMock = true
  return {
    plugins: [
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
        prodEnabled: command !== 'serve' && prodMock,
        injectCode: `
          import { setupProdMockServer } from './mockProdServer';
          setupProdMockServer();
        `,
      }),
    ],
  }
}

Sample project

meadmin template

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

Keywords

FAQs

Last updated on 23 Sep 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc