vite-plugin-mock-dev-server 0.3.18 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -85,11 +85,11 @@ export default defineConfig({
85
85
  }
86
86
  })
87
87
  ```
88
- The plugin reads the configuration for `server.proxy` and enables mock matching only for urls where the proxy is set.
88
+ The plugin reads the configuration for `server.proxy` or `options.prefix` and enables mock matching.
89
89
 
90
90
  The plugin also reads the `define` configuration and supports direct use in mock files.
91
91
 
92
- > In a general case, we only need to mock the url with the proxy so that we can proxy and mock through the http service provided by vite
92
+ > In a general case, we only need to mock the url with the proxy so that we can proxy and mock through the http service provided by vite, but you can also configure the mock using 'options.prefix'
93
93
 
94
94
  ### Edit Mock File
95
95
 
@@ -129,6 +129,16 @@ export default defineConfig({
129
129
 
130
130
  #### options
131
131
 
132
+ - `options.prefix`
133
+
134
+ Type: `string | string[]`
135
+
136
+ Configure custom matches rules for the mock server. Any requests that request path starts with that `prefix` will be proxied to that specified target. If the `prefix` starts with ^, it will be interpreted as a RegExp.
137
+
138
+ > In general, `server.proxy` is sufficient to meet the requirements, and this options is added to be compatible with some scenarios.
139
+
140
+ Default: `[]`
141
+
132
142
  - `option.include`
133
143
 
134
144
  Configure to read mock files, which can be a directory, glob, or array
package/README.zh-CN.md CHANGED
@@ -86,11 +86,12 @@ export default defineConfig({
86
86
  }
87
87
  })
88
88
  ```
89
- 插件会读取 `server.proxy` 的配置, 仅对设置了代理的 url 匹配,启用mock 匹配。
89
+ 插件会读取 `server.proxy` `options.prefix` 的配置,对匹配的 url 启用mock 匹配。
90
90
 
91
91
  插件也会读取 `define` 配置, 支持在 mock 文件中直接使用。
92
92
 
93
- > 因为一般场景下,我们只需要对有代理的url进行mock,这样才能通过 vite 提供的 http 服务进行 代理和 mock
93
+ > 因为一般场景下,我们只需要对有代理的url进行mock,这样才能通过 vite 提供的 http 服务进行 代理和 mock
94
+ > 但你也可以使用 `options.prefix`配置 mock
94
95
 
95
96
  ### 编写mock文件
96
97
 
@@ -130,6 +131,16 @@ export default defineConfig({
130
131
 
131
132
  #### options
132
133
 
134
+ - `options.prefix`
135
+
136
+ Type: `string | string[]`
137
+
138
+ 为mock服务器配置自定义匹配规则。任何请求路径以 `prefix` 值开头的请求将被代理到对应的目标。如果 `prefix` 值以 ^ 开头,将被识别为 RegExp。
139
+
140
+ > 一般情况下, `server.proxy` 已经足够满足需求,添加此项是为了与某些场景兼容。
141
+
142
+ Default: `[]`
143
+
133
144
  - `option.include`
134
145
 
135
146
  配置读取 mock文件,可以是一个 目录,glob,或者一个数组
package/dist/index.cjs CHANGED
@@ -44,7 +44,7 @@ var import_vite = require("vite");
44
44
 
45
45
  // package.json
46
46
  var name = "vite-plugin-mock-dev-server";
47
- var version = "0.3.18";
47
+ var version = "0.3.20";
48
48
 
49
49
  // src/esbuildPlugin.ts
50
50
  var import_promises = __toESM(require("fs/promises"), 1);
@@ -101,6 +101,13 @@ function getDirname(importMetaUrl) {
101
101
  return import_node_path2.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl));
102
102
  }
103
103
  var debug = (0, import_debug.default)("vite:plugin-mock-dev-server");
104
+ var ensureArray = (thing) => {
105
+ if (isArray(thing))
106
+ return thing;
107
+ if (thing === null || thing === void 0)
108
+ return [];
109
+ return [thing];
110
+ };
104
111
  function lookupFile(dir, formats, options) {
105
112
  for (const format of formats) {
106
113
  const fullPath = import_node_path2.default.join(dir, format);
@@ -119,8 +126,8 @@ function lookupFile(dir, formats, options) {
119
126
 
120
127
  // src/build.ts
121
128
  async function generateMockServer(ctx, config, options) {
122
- const include = isArray(options.include) ? options.include : [options.include];
123
- const exclude = isArray(options.exclude) ? options.exclude : [options.exclude];
129
+ const include = ensureArray(options.include);
130
+ const exclude = ensureArray(options.exclude);
124
131
  const define = {};
125
132
  if (config.define) {
126
133
  for (const key in config.define) {
@@ -128,6 +135,8 @@ async function generateMockServer(ctx, config, options) {
128
135
  define[key] = typeof val === "string" ? val : JSON.stringify(val);
129
136
  }
130
137
  }
138
+ const proxies = Object.keys(config.server.proxy || {});
139
+ const prefix = ensureArray(options.prefix);
131
140
  let pkg = {};
132
141
  try {
133
142
  const pkgStr = lookupFile(config.root, ["package.json"]);
@@ -151,7 +160,7 @@ async function generateMockServer(ctx, config, options) {
151
160
  {
152
161
  filename: import_node_path3.default.join(outputDir, "index.js"),
153
162
  source: generatorServerEntryCode(
154
- config.server.proxy || {},
163
+ [...prefix, ...proxies],
155
164
  options.build.serverPort
156
165
  )
157
166
  },
@@ -211,13 +220,12 @@ function generatePackageJson(pkg, mockDeps) {
211
220
  });
212
221
  return JSON.stringify(mockPkg, null, 2);
213
222
  }
214
- function generatorServerEntryCode(proxy = {}, port = 8080) {
215
- const proxies = Object.keys(proxy || {});
223
+ function generatorServerEntryCode(proxies, port = 8080) {
216
224
  return `import connect from 'connect'
217
225
  import { baseMiddleware } from 'vite-plugin-mock-dev-server'
218
226
  import mockData from './mock-data.js'
219
227
  const app = connect()
220
- app.use(baseMiddleware(mockData, {
228
+ app.use(baseMiddleware({ mockData }, {
221
229
  formidableOptions: { multiples: true },
222
230
  proxies: ${JSON.stringify(proxies)}
223
231
  }))
@@ -350,13 +358,14 @@ function equalObj(left, right) {
350
358
  }
351
359
 
352
360
  // src/baseMiddleware.ts
353
- function baseMiddleware(mockData, { formidableOptions = {}, proxies }) {
361
+ function baseMiddleware(mockLoader, { formidableOptions = {}, proxies }) {
354
362
  return async function(req, res, next) {
355
363
  const method = req.method.toUpperCase();
356
364
  const { query, pathname } = (0, import_node_url2.parse)(req.url, true);
357
365
  if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
358
366
  return next();
359
367
  }
368
+ const mockData = mockLoader.mockData;
360
369
  const mockUrl = Object.keys(mockData).find((key) => {
361
370
  return (0, import_path_to_regexp.pathToRegexp)(key).test(pathname);
362
371
  });
@@ -691,8 +700,8 @@ MockLoader.EXT_JSON = /\.json5?$/;
691
700
 
692
701
  // src/mockMiddleware.ts
693
702
  async function mockServerMiddleware(httpServer, config, options) {
694
- const include = isArray(options.include) ? options.include : [options.include];
695
- const exclude = isArray(options.exclude) ? options.exclude : [options.exclude];
703
+ const include = ensureArray(options.include);
704
+ const exclude = ensureArray(options.exclude);
696
705
  const define = {};
697
706
  if (config.define) {
698
707
  for (const key in config.define) {
@@ -708,14 +717,16 @@ async function mockServerMiddleware(httpServer, config, options) {
708
717
  await loader.load();
709
718
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
710
719
  const proxies = Object.keys(config.server.proxy || {});
711
- return baseMiddleware(loader.mockData, {
720
+ const prefix = ensureArray(options.prefix);
721
+ return baseMiddleware(loader, {
712
722
  formidableOptions: options.formidableOptions,
713
- proxies
723
+ proxies: [...prefix, ...proxies]
714
724
  });
715
725
  }
716
726
 
717
727
  // src/plugin.ts
718
728
  function mockDevServerPlugin({
729
+ prefix = [],
719
730
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
720
731
  exclude = [
721
732
  "**/node_modules/**",
@@ -729,6 +740,7 @@ function mockDevServerPlugin({
729
740
  build: build3 = false
730
741
  } = {}) {
731
742
  const pluginOptions = {
743
+ prefix,
732
744
  include,
733
745
  exclude,
734
746
  formidableOptions: {
package/dist/index.d.ts CHANGED
@@ -5,6 +5,13 @@ import EventEmitter from 'node:events';
5
5
  import chokidar from 'chokidar';
6
6
 
7
7
  interface MockServerPluginOptions {
8
+ /**
9
+ * 为 mock 服务配置 路径匹配规则,任何请求路径以 prefix 开头的都将被拦截代理。
10
+ * 如果 prefix 以 `^` 开头,将被识别为 `RegExp`。
11
+ *
12
+ * @default []
13
+ */
14
+ prefix?: string | string[];
8
15
  /**
9
16
  * glob 字符串匹配 mock 包含的文件
10
17
  * @see https://github.com/micromatch/picomatch#globbing-features
@@ -138,7 +145,7 @@ interface MockOptionsItem {
138
145
  type MockOptions = MockOptionsItem[];
139
146
  type FormidableFile = formidable.File | formidable.File[];
140
147
 
141
- declare function mockDevServerPlugin({ include, exclude, formidableOptions, build, }?: MockServerPluginOptions): Plugin[];
148
+ declare function mockDevServerPlugin({ prefix, include, exclude, formidableOptions, build, }?: MockServerPluginOptions): Plugin[];
142
149
 
143
150
  /**
144
151
  * mock config helper
@@ -200,6 +207,6 @@ interface BaseMiddlewareOptions {
200
207
  formidableOptions: MockServerPluginOptions['formidableOptions'];
201
208
  proxies: string[];
202
209
  }
203
- declare function baseMiddleware(mockData: MockLoader['mockData'], { formidableOptions, proxies }: BaseMiddlewareOptions): Connect.NextHandleFunction;
210
+ declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, proxies }: BaseMiddlewareOptions): Connect.NextHandleFunction;
204
211
 
205
212
  export { BaseMiddlewareOptions, FormidableFile, MockOptions, MockOptionsItem, MockServerPluginOptions, baseMiddleware, mockDevServerPlugin as default, defineMock, mockDevServerPlugin };
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { createFilter } from "vite";
9
9
 
10
10
  // package.json
11
11
  var name = "vite-plugin-mock-dev-server";
12
- var version = "0.3.18";
12
+ var version = "0.3.20";
13
13
 
14
14
  // src/esbuildPlugin.ts
15
15
  import fsp from "fs/promises";
@@ -66,6 +66,13 @@ function getDirname(importMetaUrl) {
66
66
  return path2.dirname(fileURLToPath(importMetaUrl));
67
67
  }
68
68
  var debug = Debug("vite:plugin-mock-dev-server");
69
+ var ensureArray = (thing) => {
70
+ if (isArray(thing))
71
+ return thing;
72
+ if (thing === null || thing === void 0)
73
+ return [];
74
+ return [thing];
75
+ };
69
76
  function lookupFile(dir, formats, options) {
70
77
  for (const format of formats) {
71
78
  const fullPath = path2.join(dir, format);
@@ -84,8 +91,8 @@ function lookupFile(dir, formats, options) {
84
91
 
85
92
  // src/build.ts
86
93
  async function generateMockServer(ctx, config, options) {
87
- const include = isArray(options.include) ? options.include : [options.include];
88
- const exclude = isArray(options.exclude) ? options.exclude : [options.exclude];
94
+ const include = ensureArray(options.include);
95
+ const exclude = ensureArray(options.exclude);
89
96
  const define = {};
90
97
  if (config.define) {
91
98
  for (const key in config.define) {
@@ -93,6 +100,8 @@ async function generateMockServer(ctx, config, options) {
93
100
  define[key] = typeof val === "string" ? val : JSON.stringify(val);
94
101
  }
95
102
  }
103
+ const proxies = Object.keys(config.server.proxy || {});
104
+ const prefix = ensureArray(options.prefix);
96
105
  let pkg = {};
97
106
  try {
98
107
  const pkgStr = lookupFile(config.root, ["package.json"]);
@@ -116,7 +125,7 @@ async function generateMockServer(ctx, config, options) {
116
125
  {
117
126
  filename: path3.join(outputDir, "index.js"),
118
127
  source: generatorServerEntryCode(
119
- config.server.proxy || {},
128
+ [...prefix, ...proxies],
120
129
  options.build.serverPort
121
130
  )
122
131
  },
@@ -176,13 +185,12 @@ function generatePackageJson(pkg, mockDeps) {
176
185
  });
177
186
  return JSON.stringify(mockPkg, null, 2);
178
187
  }
179
- function generatorServerEntryCode(proxy = {}, port = 8080) {
180
- const proxies = Object.keys(proxy || {});
188
+ function generatorServerEntryCode(proxies, port = 8080) {
181
189
  return `import connect from 'connect'
182
190
  import { baseMiddleware } from 'vite-plugin-mock-dev-server'
183
191
  import mockData from './mock-data.js'
184
192
  const app = connect()
185
- app.use(baseMiddleware(mockData, {
193
+ app.use(baseMiddleware({ mockData }, {
186
194
  formidableOptions: { multiples: true },
187
195
  proxies: ${JSON.stringify(proxies)}
188
196
  }))
@@ -315,13 +323,14 @@ function equalObj(left, right) {
315
323
  }
316
324
 
317
325
  // src/baseMiddleware.ts
318
- function baseMiddleware(mockData, { formidableOptions = {}, proxies }) {
326
+ function baseMiddleware(mockLoader, { formidableOptions = {}, proxies }) {
319
327
  return async function(req, res, next) {
320
328
  const method = req.method.toUpperCase();
321
329
  const { query, pathname } = urlParse(req.url, true);
322
330
  if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
323
331
  return next();
324
332
  }
333
+ const mockData = mockLoader.mockData;
325
334
  const mockUrl = Object.keys(mockData).find((key) => {
326
335
  return pathToRegexp(key).test(pathname);
327
336
  });
@@ -655,8 +664,8 @@ MockLoader.EXT_JSON = /\.json5?$/;
655
664
 
656
665
  // src/mockMiddleware.ts
657
666
  async function mockServerMiddleware(httpServer, config, options) {
658
- const include = isArray(options.include) ? options.include : [options.include];
659
- const exclude = isArray(options.exclude) ? options.exclude : [options.exclude];
667
+ const include = ensureArray(options.include);
668
+ const exclude = ensureArray(options.exclude);
660
669
  const define = {};
661
670
  if (config.define) {
662
671
  for (const key in config.define) {
@@ -672,14 +681,16 @@ async function mockServerMiddleware(httpServer, config, options) {
672
681
  await loader.load();
673
682
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
674
683
  const proxies = Object.keys(config.server.proxy || {});
675
- return baseMiddleware(loader.mockData, {
684
+ const prefix = ensureArray(options.prefix);
685
+ return baseMiddleware(loader, {
676
686
  formidableOptions: options.formidableOptions,
677
- proxies
687
+ proxies: [...prefix, ...proxies]
678
688
  });
679
689
  }
680
690
 
681
691
  // src/plugin.ts
682
692
  function mockDevServerPlugin({
693
+ prefix = [],
683
694
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
684
695
  exclude = [
685
696
  "**/node_modules/**",
@@ -693,6 +704,7 @@ function mockDevServerPlugin({
693
704
  build: build3 = false
694
705
  } = {}) {
695
706
  const pluginOptions = {
707
+ prefix,
696
708
  include,
697
709
  exclude,
698
710
  formidableOptions: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-mock-dev-server",
3
- "version": "0.3.18",
3
+ "version": "0.3.20",
4
4
  "keywords": [
5
5
  "vite",
6
6
  "plugin",
@@ -33,11 +33,11 @@
33
33
  "chokidar": "^3.5.3",
34
34
  "co-body": "^6.1.0",
35
35
  "debug": "^4.3.4",
36
- "esbuild": "^0.16.9",
36
+ "esbuild": "^0.17.6",
37
37
  "fast-glob": "^3.2.12",
38
38
  "formidable": "^2.1.1",
39
39
  "is-core-module": "^2.11.0",
40
- "json5": "^2.2.2",
40
+ "json5": "^2.2.3",
41
41
  "path-to-regexp": "^6.2.1"
42
42
  },
43
43
  "devDependencies": {
@@ -47,22 +47,22 @@
47
47
  "@types/debug": "^4.1.7",
48
48
  "@types/formidable": "^2.0.5",
49
49
  "@types/is-core-module": "^2.2.0",
50
- "@types/node": "^18.11.7",
50
+ "@types/node": "^18.11.19",
51
51
  "bumpp": "^8.2.1",
52
52
  "conventional-changelog-cli": "^2.2.2",
53
- "eslint": "^8.31.0",
53
+ "eslint": "^8.33.0",
54
54
  "mockjs": "^1.1.0",
55
- "prettier": "^2.8.1",
55
+ "prettier": "^2.8.3",
56
56
  "tsup": "^6.5.0",
57
- "typescript": "^4.9.4",
58
- "vite": "^4.0.2",
59
- "vitepress": "1.0.0-alpha.35",
60
- "vue": "^3.2.45"
57
+ "typescript": "^4.9.5",
58
+ "vite": "^4.1.1",
59
+ "vitepress": "1.0.0-alpha.45",
60
+ "vue": "^3.2.47"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "vite": ">=3.0.0"
64
64
  },
65
- "packageManager": "pnpm@7.18.2",
65
+ "packageManager": "pnpm@7.26.3",
66
66
  "engines": {
67
67
  "node": "^14.18.0 || >=16"
68
68
  },