npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mock-service-plugin

v1.8.8

Published

Simulated backend interface service

Readme

mock-service-plugin

English | 中文

A powerful Mock service plugin that supports multiple frameworks and build tools, providing flexible interface simulation capabilities.

Features

  • 🚀 Support for multiple build tools
    • Webpack 4/5
    • Vite
    • Vue CLI
    • Create React App (CRA)
  • 🎯 Support for multiple frameworks
    • Vue
    • React
  • 🔥 Powerful feature support
    • RESTful API support
    • Streaming responses (SSE/EventStream)
    • Multiple response formats (JSON/XML/CSV/Text etc.)
    • Dynamic route parameters
    • Request method matching (GET/POST/PUT/DELETE etc.)
  • 💡 Easy to use
    • Zero configuration startup
    • Hot reload support
    • Friendly debugging interface

Quick Start

Installation

npm install mock-service-plugin --save-dev

yarn add mock-service-plugin --dev

Basic Configuration

const MockServicePlugin = require("mock-service-plugin");

module.exports = {
  plugins: [
    new MockServicePlugin({
      mockDir: path.join(__dirname, "./mocks"), // mock data directory
      port: 3000, // mock service port
    }),
  ],
};

Mock Data Specification

Basic Format

/**
 * @url /api/users
 * @method GET
 */
{
  "code": 200,
  "data|5-10": [{
    "id": "@id",
    "name": "@cname",
    "email": "@email"
  }],
  "message": "success"
}

Header Annotation Description

/**
 * @url /api/users
 * @method GET
 */
  • @url: Interface path (required)
  • @method: Request method (optional, supports GET/POST/PUT/DELETE etc., case-insensitive)

Request Method Matching

  1. Specify request method:
/**
 * @url /api/users
 * @method POST
 */
{
  "code": 200,
  "message": "Created successfully"
}
  1. Support all request methods (without @method):
/**
 * @url /api/users
 */
{
  "code": 200,
  "data": {
    "id": "@id",
    "name": "@cname"
  }
}
  1. RESTful API example:
// POST request
/**
 * @url /api/users
 * @method POST
 */
{
  "code": 200,
  "message": "Created successfully"
}

// GET request
/**
 * @url /api/users/:id
 * @method GET
 */
{
  "id": "@id",
  "name": "@cname"
}

// PUT request
/**
 * @url /api/users/:id
 * @method PUT
 */
{
  "code": 200,
  "message": "Updated successfully"
}

// DELETE request
/**
 * @url /api/users/:id
 * @method DELETE
 */
{
  "code": 200,
  "message": "Deleted successfully"
}

Supported Response Types

| Mock file extension | Content-Type | Description | | ------------------- | ---------------------- | ----------------- | | .json | application/json | JSON data format | | .txt | text/plain | Plain text format | | .html | text/html | HTML document | | .xml | application/xml | XML data format | | .csv | text/csv | CSV table data | | .md | text/markdown | Markdown document | | .pdf | application/pdf | PDF document | | .png | image/png | PNG image | | .jpg/.jpeg | image/jpeg | JPEG image | | .gif | image/gif | GIF image | | .svg | image/svg+xml | SVG vector image | | .css | text/css | CSS stylesheet | | .js | application/javascript | JavaScript code | | .yaml/.yml | application/x-yaml | YAML config file | | .sse | text/event-stream | SSE event stream |

Mock File Examples

JSON Format (mock.json)

/**
 * @url /api/users
 * @method GET
 */
{
  "code": 200,
  "data": {
    "name": "@cname",
    "age": "@integer(18, 60)"
  }
}

Text Format (mock.txt)

/**
 * @url /api/text
 * @method GET
 */
This is a mock text content, supporting multiple lines.
Second line content.
Third line content.

CSS Format (mock.css)

/**
 * @url /api/styles
 * @method GET
 */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

Markdown Format (mock.md)

/**
 * @url /api/markdown
 * @method GET
 */
# Heading 1
## Heading 2
- List item 1
- List item 2

YAML Format (mock.yaml)

/**
 * @url /api/config
 * @method GET
 */
version: 1.0;
settings: debug: true;
timeout: 30;

CSV Format (mock.csv)

/**
 * @url /api/data
 * @method GET
 */
(id, name, age);
(1, John, 25);
(2, Jane, 30);
(3, Bob, 28);

XML Format (mock.xml)

/**
 * @url /api/xml
 * @method GET
 */
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <user>
    <name>John</name>
    <age>25</age>
  </user>
</root>

JavaScript Format (mock.js)

/**
 * @url /api/script
 * @method GET
 */
function greeting(name) {
  return `Hello, ${name}!`;
}

For image type responses, you can directly return the image file path:

/**
 * @url /api/avatar
 * @content-type image/png
 */
"/path/to/avatar.png";

Advanced Features

RESTful API Support

/**
 * @url /api/users/:id
 * @method GET
 */
{
  "id": "@id",
  "name": "@cname",
  "email": "@email"
}

Streaming Response

File extension: mock.sse

/**
 * @url /api/stream
 */
{
  "interval": "@integer(100,500)",
  "items|10": [{
    "id": "@increment(1)",
    "data": {
      "content": "@csentence(3,10)"
    }
  }]
}

Framework Integration

Vue Project

// vue.config.js
const MockServicePlugin = require("mock-service-plugin");

module.exports = {
  configureWebpack: {
    plugins: [
      new MockServicePlugin({
        mockDir: path.join(__dirname, "./mocks"),
        port: 9090,
      }),
    ],
  },
  devServer: {
    proxy: {
      "/api": {
        target: "http://localhost:9090",
        pathRewrite: { "^/api": "" },
      },
    },
  },
};

React Project (CRA)

Using craco

// craco.config.js
const MockServicePlugin = require("mock-service-plugin");

module.exports = {
  webpack: {
    plugins: {
      add: [
        new MockServicePlugin({
          mockDir: path.join(__dirname, "./mocks"),
          port: 9090,
        }),
      ],
    },
  },
};

Using customize-cra

// config-overrides.js
const { override, addWebpackPlugin } = require("customize-cra");
const MockServicePlugin = require("mock-service-plugin");

module.exports = override(
  addWebpackPlugin(
    new MockServicePlugin({
      mockDir: path.join(__dirname, "./mocks"),
      port: 9090,
    })
  )
);

Vite Project

// vite-mock-plugin.ts file
import { startServer } from 'mock-service-plugin'
import { createServer } from 'net'
import { join } from 'path'

function isPortTaken(port: number) {
  return new Promise((resolve) => {
    const server = createServer()

    server.once('error', (err: { code: string }) => {
      if (err.code === 'EADDRINUSE') {
        resolve(true)
      } else {
        resolve(false)
      }
    })

    server.once('listening', () => {
      server.close()
      resolve(false)
    })

    server.listen(port)
  })
}

export default function ViteMockServicePlugin(e: string) {
  return {
    name: 'ViteMockServicePlugin',
    buildStart() {
      ;(async () => {
        const port = 3008
        const portTaken = await isPortTaken(port)
        if (portTaken) {
          console.log(`Port ${port} is already in use`)
        } else {
          if (e === 'mock') {
            // 启动本地 mock 服务(startServer 无需返回值)
            startServer({
              // Path for mock data
              mockDir: join(__dirname, './src/mock'),
              // Configure mock service port to avoid conflicts with application port
              port: 3008,
            })
          }
        }
      })()
    },
  }
}
// vite.config.ts
import { defineConfig } from "vite";
// The vite-mock-plugin imported here is the code snippet above
import ViteMockServicePlugin from "./vite-mock-plugin";

export default defineConfig({ mode })=>{
  return {
    plugins: [ViteMockServicePlugin(mode)],
  }
});
# .env.mock
VITE_SEVER_URL=http://localhost:3008/
// package.json
{
  "scripts": {
    "dev": "vite --mode dev",
    // add mock script
    "mock": "vite --mode mock",
  },
}

Example Projects

Notes

  1. Page refresh required after modifying mock data
  2. Ensure mock service port doesn't conflict with application port
  3. Recommended to use relative paths for mock data directory configuration

Contributing

Issues and Pull Requests are welcome

License

MIT