Gathering detailed insights and metrics for mock-service-plugin
Gathering detailed insights and metrics for mock-service-plugin
npm install mock-service-plugin
Typescript
Module System
Node Version
NPM Version
JavaScript (60.95%)
HTML (39.05%)
Total Downloads
3,355
Last Day
4
Last Week
24
Last Month
361
Last Year
1,721
1 Stars
43 Commits
1 Watching
1 Branches
1 Contributors
Minified
Minified + Gzipped
Latest Version
1.2.2
Package Id
mock-service-plugin@1.2.2
Unpacked Size
28.43 kB
Size
10.86 kB
File Count
9
NPM Version
10.8.2
Node Version
22.5.1
Publised On
19 Nov 2024
Cumulative downloads
Total Downloads
Last day
-69.2%
4
Compared to previous day
Last week
-70.7%
24
Compared to previous week
Last month
34.2%
361
Compared to previous month
Last year
89.3%
1,721
Compared to previous year
前后端分离并行开发,模拟后端接口服务
1npm i mock-service-plugin --save-dev
1new MockServicePlugin(options);
.
├── app //工程目录
├── dist
├── config
├── src
├── mocks //mock数据目录
| ├── data.js
| ├── data.json
...
Mock 数据
并非严格的 json 格式数据文件,更像是 js 代码。
当我们只需要返回直接的数据结构,使用如下的 json 格式会显得非常直接,示例data.json
如下:
1/** 2 * @url /login 3 * @method POST 4 * @title 登录接口 5 * @content 说明 6 * @param {string} userid 7 * @param {string} password 8 */ 9{ 10 "code": 404, 11 "data|5-10": [ 12 { 13 "name": "@cname", 14 "id": "@guid", 15 "email": "@email" 16 } 17 ], 18 "message": "success" 19}
对应的文件内容可以这样理解
访问路径
(必填项)接口名称
(非必填)以上 mock 数据的语法均来自 mockjs
,想获取更多语法可以参阅 mockjs 官网文档和示例
mock 数据说明文档和功能来源于 52cik/express-mockjs
增加 mock 数据时,在 mock 中新建文件即可,webpack 配置无需更新,但是需要刷新界面
分为三部分讲解:
在工程目录中增加一个 mocks
文件夹
.
├── app //工程目录
├── dist
├── config
├── src
├── mocks //mock数据目录
| ├── data.js
| ├── data.json
...
在 webpack.config.js
中,配置 proxy 和 mock-service-plugin
1// 引入插件 2const MockServicePlugin = require("mock-service-plugin"); 3 4// webpack 配置 5module.exports = { 6 // 配置插件 7 plugins: [ 8 // 插件的功能是根据配置文件,起一个指定端口的server,将接口请求指向json文件 9 new MockServicePlugin({ 10 // mock数据的存放路径 11 path: path.join(__dirname, "./mocks"), 12 // 配置mock服务的端口,避免与应用端口冲突 13 port: 3000, 14 }), 15 ], 16 // 配置代理,这里的代理为webpack自带功能 17 devServer: { 18 // 应用端口,避免与mock服务端口冲突 19 port: 5001, 20 proxy: { 21 // 配置匹配服务的url规则,以及其代理的服务地址,即mock服务的地址 22 "/": "http://localhost:3000/", 23 }, 24 }, 25};
如果想要给 mock 服务指定 URL 前缀,你可以在 webpack 的 proxy 设置进行如下配置:
1... 2module.exports = { 3 ... 4 // 配置代理,这里的代理为webpack自带功能 5 devServer: { 6 // 应用端口,避免与mock服务端口冲突 7 port: 5001, 8 proxy: { 9 '/api': { 10 target: 'http://localhost:3000/', 11 pathRewrite: { 12 // 设置url的重写, 实际过程如下: 13 // http://localhost:5001/api/getData -> http://localhost:3000/getData 14 '^/api': '' 15 } 16 } 17 } 18 } 19};
安装 mock-service-plugin
1npm i mock-service-plugin --save-dev
在 vue.config.js
配置 mock-service-plugin
1// 引入插件 2const MockServicePlugin = require("mock-service-plugin"); 3 4module.exports = { 5 configureWebpack: { 6 // 在 plugins 初始化插件 7 plugins: [ 8 // 初始化 9 new MockServicePlugin({ 10 path: path.join(__dirname, "./mocks"), // mock数据存放在 mocks 文件夹中 11 port: 9090, // 服务端口号 12 }), 13 ], 14 }, 15};
项目根目录下创建 mock 数据文件夹 mocks
如下图
在mocks
文件夹下创建一个data.json
文件
添加如下数据(一个文件里仅仅放一个接口的 mock 数据,文件名随意)
1/** 2 * @url /login 3 */ 4{ 5 "code": 404, 6 "data|5-10": [ 7 { 8 "name": "@cname", 9 "id": "@guid", 10 "email": "@email" 11 } 12 ], 13 "message": "success" 14}
说明:
以获取用户信息接口为例( www.example.com/user/info
),我们通常会把www.example.com
作为 baseUrl
,user/info
作为接口 URL,在 data.json 文件文件中的 /login
就相当于user/info
(图片懒得换了你们懂就行),
头部注释中的 @url
字段是必须的,当请求发送到 mock 服务器上时, mock 服务会遍历mocks
文件夹下所有的.json
文件, 将请求 url 与头部注释 @url 中的字段匹配, 匹配成功返回 json
中的数据
添加好以上信息后重启项目 (注意控制台输出)
在浏览器中打开 http://localhost:9090
点击左侧列表中 /login
如果看到上面的页面说明我们 mock 服务搭建成功了,接下来只要把请求发送到 mock 服务器上就可以了下面我们来实现下吧
将请求发送到 http://localhost:9090
, 在vue.config.js
中配下代理 就可以了
1 // 配置代理 2 devServer: { 3 // 应用端口,避免与mock服务端口冲突 4 port: 3000, 5 proxy: { 6 '/api': { 7 target: 'http://localhost:9090/', 8 pathRewrite: { 9 // 设置url的重写, 实际过程如下: 10 // http://localhost:5001/api/getData -> http://localhost:3000/getData 11 '^/api': '' 12 } 13 } 14 } 15 }
设置 axios 的 baseUrl
为 api
就可以了 这一步很简单,把我的配置贴在下面,根据实际情况自行调整哈
在项目中使用
在页面上测试下
Vue 项目的 mock 服务就搭建完成了
CRA 官方并没有开放 Webpack 的配置,有两种解决方式,第一种弹出 webpack 配置,第二种社区适配方案,社区适配方案主流有两种 craco
与 customize-cra
因为这两种方式都有人用,分别介绍下,建议将 Vue 配置教程详细阅读一遍,主要看配置流程,原理其实都一样
npm i mock-service-plugin --save-dev
1// craco.config.js 2 3import path from "path"; 4 5import { whenDev } from "@craco/craco"; 6 7// mock 插件 8import MockServicePlugin from "mock-service-plugin"; 9 10const { 11 REACT_APP_ENV, // 环境标识 12} = process.env; 13 14const pathResolve = (pathUrl) => path.join(__dirname, pathUrl); 15 16module.exports = { 17 webpack: { 18 plugins: [ 19 ...whenDev( 20 () => [ 21 // 配置mock服务 22 new MockServicePlugin({ 23 path: path.join(__dirname, "./mocks"), 24 port: 9090, 25 }), 26 ], 27 [] 28 ), 29 ], 30 }, 31 devServer: { 32 proxy: { 33 "/mock": { 34 secure: false, 35 ws: false, 36 target: `http://localhost:9090`, 37 changeOrigin: true, 38 pathRewrite: { 39 "^/mock": "", 40 }, 41 }, 42 }, 43 }, 44};
1// config.overrides.js 2 3const path = require("path"); 4 5const { 6 override, // 覆盖函数 7 addWebpackAlias, // 别名配置 8 addLessLoader, // less loader 9 fixBabelImports, // babel 导入 引入antd-mobile 10 addWebpackPlugin, // 增加插件 11} = require("customize-cra"); 12 13// mock 插件 14const MockServicePlugin = require("mock-service-plugin"); 15 16const { 17 REACT_APP_ENV, // 环境标识 18} = process.env; 19 20/** 21 * @description: 路径 处理 22 * @param {String} pathUrl 23 * @return {String} path 24 */ 25const pathResolve = (pathUrl) => path.join(__dirname, pathUrl); 26 27// override 28module.exports = { 29 webpack: override( 30 addWebpackPlugin( 31 // 配置mock服务 32 new MockServicePlugin({ 33 path: path.join(__dirname, "./mocks"), 34 port: 9090, 35 }) 36 ), 37 (config) => { 38 return config; 39 } 40 ), 41 devServer: (configFunction) => (proxy, allowedHost) => { 42 proxy = { 43 "/mock": { 44 secure: false, 45 ws: false, 46 target: `http://localhost:9090`, 47 changeOrigin: true, 48 pathRewrite: { 49 "^/mock": "", 50 }, 51 }, 52 }; 53 return configFunction(proxy, allowedHost); 54 }, 55};
1import MockServicePlugin from "mock-service-plugin"; 2import net from "net"; 3import path from "path"; 4 5function isPortTaken(port: number) { 6 return new Promise((resolve) => { 7 const server = net.createServer(); 8 9 server.once("error", (err: { code: string }) => { 10 if (err.code === "EADDRINUSE") { 11 resolve(true); 12 } else { 13 resolve(false); 14 } 15 }); 16 17 server.once("listening", () => { 18 server.close(); 19 resolve(false); 20 }); 21 22 server.listen(port); 23 }); 24} 25 26// eslint-disable-next-line import/no-default-export 27export default function ViteMockServicePlugin(e: string) { 28 return { 29 name: "ViteMockServicePlugin", 30 buildStart() { 31 (async () => { 32 const port = 3008; 33 const portTaken = await isPortTaken(port); 34 if (portTaken) { 35 console.log(`Port ${port} is already in use`); 36 } else { 37 if (e === "mock") { 38 const ints = new MockServicePlugin({ 39 // mock 数据的存放路径 40 path: path.join(__dirname, "./mocks"), 41 // 配置mock服务的端口,避免与应用端口冲突 42 port: 3008, 43 }); 44 ints.apply(); 45 } 46 } 47 })(); 48 }, 49 }; 50}
vite.config.ts
文件1import react from "@vitejs/plugin-react"; 2 3import ViteMockServicePlugin from "./vite-mock-plugin"; 4 5export default defineConfig(({ mode }) => { 6 return { 7 plugins: [react(), ViteMockServicePlugin(mode)], 8 }; 9});
支持 RESTful API
/llm/:schema/:type/:id/txt/v2
支持流式传输
LLM、 SSE、 EventStream 响应
以下是流模式及 RESTful api 使用示例
1/** 2 * @url /llm/:schema/:type/:id/txt/v2 3 * RESTful API endpoint for streaming LLM responses 4 * 下面是 流模式 响应固定格式, 5 * 必须包含 "stream": true, 6 * 必须包含 "interval": "100" 7 * 其他字段不是必须的,根据 业务需求自定义 8 */ 9{ 10 "stream": true, // 是否为流模式 11 "interval": "@integer(100,500)", // 间隔响应时间 12 "items|50": [ 13 { 14 "id": "@increment(1)", 15 "data": { 16 "id": "@guid", 17 "object": "chat.completion.chunk", 18 "created": "@now('T')", 19 "model": "@pick(['moonshot-v1-8k', 'moonshot-v1-16k', 'moonshot-v1-32k'])", 20 "choices": [ 21 { 22 "index": 0, 23 "delta": { 24 "role": "assistant", 25 "content": "@csentence(3,10)" 26 }, 27 "finish_reason": null 28 } 29 ], 30 "system_fingerprint": "fpv0_@string('lower',8)" 31 } 32 } 33 ] 34}
No vulnerabilities found.
No security vulnerabilities found.