vite-plugin-mock-dev-server 1.0.5 → 1.0.7

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
@@ -26,21 +26,22 @@
26
26
 
27
27
  ## Feature
28
28
 
29
- - ⚡️ light weight,flexible,fast
30
- - 🧲 Non - injection, no intrusion to client code
31
- - 💡 ESModule/commonjs
32
- - 🦾 Typescript
33
- - 🏷 Support json / json5
34
- - 📦 Auto import mock file
29
+ - ⚡️ light weight,flexible,fast.
30
+ - 🧲 Not injection-based, non-intrusive to client code.
31
+ - 💡 ESModule/commonjs.
32
+ - 🦾 Typescript.
33
+ - 🏷 Support `json` / `json5`.
34
+ - 📦 Auto import mock file.
35
35
  - 🎨 Support any lib,like `mockjs`,or not use it.
36
- - 📥 Path rules match and request parameters match
36
+ - 📥 Path rule matching, request parameter matching.
37
37
  - ⚙️ Support Enabled/Disabled any one of api mock
38
38
  - 🔥 HMR
39
39
  - ⚖️ Use `server.proxy`
40
40
  - 🍕 Support `viteConfig.define` in mock file
41
+ - ⚓️ Support `resolve.alias`
41
42
  - 📤 Support `multipart` content-type,mock upload file.
42
43
  - 🌈 Support `vite preview` mode
43
- - 🗂 Support for building independently deployed mock services
44
+ - 🗂 Support building small independent deployable mock services.
44
45
 
45
46
 
46
47
  ## Documentation
@@ -77,6 +78,7 @@ export default defineConfig({
77
78
  plugins: [
78
79
  mockDevServerPlugin(),
79
80
  ],
81
+ // The fields defined here can also be used in mock.
80
82
  define: {},
81
83
  server: {
82
84
  proxy: {
@@ -87,15 +89,17 @@ export default defineConfig({
87
89
  }
88
90
  })
89
91
  ```
90
- The plugin reads the configuration for `server.proxy` or `options.prefix` and enables mock matching.
92
+ The plugin will read the configuration of `server.proxy` or `options.prefix`, and enable mock matching for matched URLs.
91
93
 
92
- The plugin also reads the `define` configuration and supports direct use in mock files.
94
+ The plugin will also read the `define` configuration, which supports direct use in mock files.
93
95
 
94
- > 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'
96
+ > Because in general scenarios, we only need to mock URLs with proxies so that we can use the proxy and mock services provided by Vite's HTTP service.
97
+ >
98
+ > However, you can also configure mocks using `options.prefix`.
95
99
 
96
100
  ### Edit Mock File
97
101
 
98
- By default, write mock data in the `mock` directory of your project root:
102
+ By default, write mock data in the `mock` directory of your project's root directory:
99
103
 
100
104
  `mock/api.mock.ts` :
101
105
  ```ts
@@ -129,15 +133,16 @@ export default defineConfig({
129
133
  })
130
134
  ```
131
135
 
136
+
132
137
  #### options
133
138
 
134
139
  - `options.prefix`
135
140
 
136
141
  **Type:** `string | string[]`
137
142
 
138
- 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.
143
+ Configure custom matching rules for mock server. Any request path starting with the value of `prefix` will be proxied to the corresponding target. If the `prefix` value starts with ^, it will be recognized as a RegExp.
139
144
 
140
- > In general, `server.proxy` is sufficient to meet the requirements, and this options is added to be compatible with some scenarios.
145
+ > In general, `server.proxy` is sufficient to meet the needs. Adding this item is for compatibility with certain scenarios.
141
146
 
142
147
  **Default:** `[]`
143
148
 
@@ -145,25 +150,22 @@ export default defineConfig({
145
150
 
146
151
  **Type:** `string | string[]`
147
152
 
148
- Configure to read mock files, which can be a directory, glob, or array
153
+ Configure to read mock files, which can be a directory, glob, or an array.
149
154
 
150
- **Default:** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` (relative for `process.cwd()`)
155
+ **Default:** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` (Relative to the root directory.)
151
156
 
152
157
  - `options.exclude`
153
158
 
154
159
  **Type:** `string | string[]`
155
160
 
156
- When you configure the mock files to be read, the files you want to exclude can be a directory, glob, or array
161
+ When reading mock files for configuration, the files that need to be excluded can be a directory, glob, or an array.
157
162
 
158
163
  **Default:**
159
164
  ```ts
160
165
  [
161
166
  '**/node_modules/**',
162
- '**/test/**',
163
- 'src/**',
164
167
  '**/.vscode/**',
165
168
  '**/.git/**',
166
- '**/dist/**'
167
169
  ]
168
170
  ```
169
171
 
@@ -171,8 +173,7 @@ export default defineConfig({
171
173
 
172
174
  **Type:** `boolean`
173
175
 
174
- When mock resources are hot reload, only the data content is updated, but the page is not refreshed by default.
175
- Turn this on when you want to refresh the page every time you modify the mock file.
176
+ When the mock resource is hot updated, only the data content is updated, but the page is not refreshed by default. If you want to refresh the page every time you modify the mock file, you can open this option.
176
177
 
177
178
 
178
179
  **Default:** `false`
@@ -194,7 +195,7 @@ export default defineConfig({
194
195
 
195
196
  - `options.build`
196
197
 
197
- When building a small, independently deployable mock service.
198
+ Configuration needed to build a small, independently deployable mock service.
198
199
 
199
200
  **Type:** `boolean | ServerBuildOptions`
200
201
 
@@ -228,16 +229,34 @@ export default defineMock({
228
229
  })
229
230
  ```
230
231
 
232
+ ### createDefineMock(transformer)
233
+
234
+ Return a custom defineMock function to support preprocessing of mock config.
235
+
236
+ ```ts
237
+ import path from 'path'
238
+ import { createDefineMock } from 'vite-plugin-mock-dev-server'
239
+
240
+ // Preprocessed mock url
241
+ const defineAPIMock = createDefineMock((mock) => {
242
+ mock.url = path.join('/api', mock.url)
243
+ })
244
+
245
+ export default defineApiMock({
246
+ url: '/test' // Complete as '/api/test'
247
+ })
248
+ ```
249
+
231
250
  ## Mock Configuration
232
251
 
233
252
  ```ts
234
253
  export default defineMock({
235
254
  /**
236
- * Address of request,and support like `/api/user/:id`
255
+ * Request address, supports the `/api/user/:id` format.
237
256
  */
238
257
  url: '/api/test',
239
258
  /**
240
- * The request method supported by the API
259
+ * Supported request methods of the interface.
241
260
  *
242
261
  * @type string | string[]
243
262
  * @default ['POST','GET']
@@ -245,16 +264,17 @@ export default defineMock({
245
264
  */
246
265
  method: ['GET', 'POST'],
247
266
  /**
248
- * enable/disable the current mock request
249
- *
250
- * we typically only need a few mock interfaces to work.
251
- * set `false` to disable current mock
267
+ * In practical scenarios,
268
+ * we usually only need certain mock interfaces to take effect,
269
+ * rather than enabling all mock interfaces.
270
+ * For interfaces that do not currently require mocking,
271
+ * they can be set to false.
252
272
  *
253
273
  * @default true
254
274
  */
255
275
  enable: true,
256
276
  /**
257
- * response delay unitms
277
+ * Set interface response delay, unit: ms.
258
278
  *
259
279
  * @default 0
260
280
  */
@@ -270,27 +290,23 @@ export default defineMock({
270
290
  */
271
291
  statusText: 'OK',
272
292
  /**
273
- * Request a validator, through which the mock data
274
- * is returned, otherwise not the current mock.
275
- * In some scenarios where an interface needs to
276
- * return different data through different inputs,
277
- * the validator can solve this kind of problem well.
278
- * It divides the same url into multiple mock
279
- * configurations and determines which mock configuration
280
- * is valid according to the validator.
293
+ * Request validator, return mock data if validated, otherwise do not use current mock.
294
+ * This is useful in scenarios where an interface needs to return different data based
295
+ * on different input parameters.
296
+ * Validators can solve this type of problem well by dividing the same URL into multiple
297
+ * mock configurations and determining which one is effective based on the validator.
281
298
  *
282
299
  * @type { headers?: object; body?: object; query?: object; params?: object; refererQuery?: object }
283
300
  *
284
- * If the validator incoming is an object,
285
- * then the validation method is the comparison of the
286
- * strict request of interface, headers/body/query/params
287
- * each `key-value` congruent, congruent check through
301
+ * If the validator passes in an object,
302
+ * then the validation method is to strictly compare whether the `value`
303
+ * of each `key` in headers/body/query/params in the request interface is exactly equal.
304
+ * If they are all equal, then the validation passes.
288
305
  *
289
306
  * @type ({ headers: object; body: object; query: object; params: object; refererQuery: object }) => boolean
290
- * If the validator is passed a function,
291
- * it takes the requested interface-related data as an input,
292
- * gives it to the consumer for custom validation,
293
- * and returns a boolean
307
+ * If the validator passed in is a function,
308
+ * then the data related to the requested interface will be provided as input parameters
309
+ * for users to perform custom validation and return a boolean.
294
310
  *
295
311
  */
296
312
  validator: {
@@ -299,9 +315,9 @@ export default defineMock({
299
315
  query: {},
300
316
  params: {},
301
317
  /**
302
- * refererQuery validates the query in the url of the page from which the request originated,
303
- * which makes it possible to modify parameters directly in the browser address bar to get
304
- * different mock data
318
+ * refererQuery validates the query parameters in the URL of the request source page,
319
+ * which allows for direct modification of parameters in the browser address bar
320
+ * to obtain different simulated data.
305
321
  */
306
322
  refererQuery: {}
307
323
  },
@@ -329,9 +345,11 @@ export default defineMock({
329
345
  body: {},
330
346
 
331
347
  /**
332
- * If the mock requirement cannot be addressed with the body configuration,
333
- * Then you can expose the http server interface by configuring response,
334
- * Achieve fully controlled custom configuration.
348
+ * If the mock requirement cannot be solved through `body` configuration,
349
+ * then it can be achieved by configuring response and exposing the interface of http server
350
+ * to realize fully controllable custom configuration in req parameters.
351
+ * The parsing of query, body and params has been built-in, so you can use them directly.
352
+ * Don't forget to return response data through `res.end()` or skip mock by calling `next()`.
335
353
  */
336
354
  response(req, res, next) {
337
355
  res.end()
@@ -558,11 +576,11 @@ export default defineMock({
558
576
 
559
577
  ## Mock Services
560
578
 
561
- In some scenarios, you may need to use the data support provided by the mock service for display purposes, but it is possible that the project has been packaged and deployed as a build and is out of the mock service support provided by `vite` and this plugin. Since this plugin was designed to support the import of `node` modules into mock files, it cannot package mock files inline into client-side build code.
579
+ In some scenarios, it may be necessary to use the data provided by mock services for display purposes, but the project may have already been packaged, built and deployed without support from `vite` and this plugin's mock service. Since this plugin supports importing various `node` modules in mock files at the design stage, the mock file cannot be inline into client build code.
562
580
 
563
- To cater for such scenarios, the plugin provides support under `vite preview` as well as the ability to build a small, independently deployable mock service application at `vite build` that can be deployed to the relevant environment. The mock support is then implemented by proxy forwarding to the actual port by another http server such as `nginx`.
581
+ To meet such scenarios, on one hand, the plugin provides support under `vite preview`, and on the other hand, it also builds a small independent mock service application that can be deployed to relevant environments during `vite build`. This can then be forwarded through other HTTP servers like nginx to actual ports for mock support.
564
582
 
565
- Build the default output into the `dist/mockServer` directory and generate the following file:
583
+ The default output is built into the directory `dist/mockServer`, generating files as follows:
566
584
  ```sh
567
585
  ./mockServer
568
586
  ├── index.js
@@ -570,11 +588,11 @@ Build the default output into the `dist/mockServer` directory and generate the f
570
588
  └── package.json
571
589
  ```
572
590
 
573
- In this directory, after `npm install` to install the dependencies, `npm start` can be executed to start the mock server.
591
+ In this directory, execute `npm install` to install dependencies, and then execute `npm start` to start the mock server.
574
592
 
575
- default port: `8080`。
593
+ The default port is `8080`.
576
594
 
577
- Access the associated `mock` interface via `localhost:8080/`.
595
+ You can access related `mock` interfaces through `localhost:8080/`.
578
596
 
579
597
  ## Archives
580
598
 
package/README.zh-CN.md CHANGED
@@ -31,7 +31,7 @@
31
31
  - 🧲 非注入式,对客户端代码无侵入
32
32
  - 💡 ESModule/commonjs
33
33
  - 🦾 Typescript
34
- - 🏷 支持 json / json5 编写 mock 数据
34
+ - 🏷 支持 `json` / `json5` 编写 mock 数据
35
35
  - 📦 自动加载 mock 文件
36
36
  - 🎨 可选择你喜欢的任意用于生成mock数据库,如 `mockjs`,或者不使用其他库
37
37
  - 📥 路径规则匹配,请求参数匹配
@@ -39,6 +39,7 @@
39
39
  - 🔥 热更新
40
40
  - ⚖️ 使用 `server.proxy` 配置
41
41
  - 🍕 支持在 mock文件中使用 `viteConfig.define`配置字段
42
+ - ⚓️ 支持 `resolve.alias`
42
43
  - 📤 支持 multipart 类型,模拟文件上传
43
44
  - 🌈 支持 `vite preview` 模式
44
45
  - 🗂 支持构建可独立部署的小型mock服务
@@ -161,11 +162,8 @@ export default defineConfig({
161
162
  ```ts
162
163
  [
163
164
  '**/node_modules/**',
164
- '**/test/**',
165
- 'src/**',
166
165
  '**/.vscode/**',
167
166
  '**/.git/**',
168
- '**/dist/**'
169
167
  ]
170
168
  ```
171
169
 
@@ -194,7 +192,7 @@ export default defineConfig({
194
192
 
195
193
  - `options.build`
196
194
 
197
- 构建可独立部署的小型mock服务时配置。
195
+ 需要构建可独立部署的小型mock服务时配置。
198
196
 
199
197
  **类型:** `boolean | ServerBuildOptions`
200
198
 
@@ -228,6 +226,24 @@ export default defineMock({
228
226
  })
229
227
  ```
230
228
 
229
+ ### createDefineMock(transformer)
230
+
231
+ 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
232
+
233
+ ```ts
234
+ import path from 'path'
235
+ import { createDefineMock } from 'vite-plugin-mock-dev-server'
236
+
237
+ // 预处理 mock url
238
+ const defineAPIMock = createDefineMock((mock) => {
239
+ mock.url = path.join('/api', mock.url)
240
+ })
241
+
242
+ export default defineApiMock({
243
+ url: '/test' // 补全为 '/api/test'
244
+ })
245
+ ```
246
+
231
247
  ## Mock 配置
232
248
 
233
249
  ```ts
@@ -271,7 +287,7 @@ export default defineMock({
271
287
  */
272
288
  statusText: 'OK',
273
289
  /**
274
- * 请求验证器,通过验证器则返回 mock数据,否则不是用当前mock。
290
+ * 请求验证器,通过验证器则返回 mock数据,否则不使用当前mock。
275
291
  * 这对于一些场景中,某个接口需要通过不同的入参来返回不同的数据,
276
292
  * 验证器可以很好的解决这一类问题,将同个 url 分为多个 mock配置,
277
293
  * 根据 验证器来判断哪个mock配置生效。
@@ -292,9 +308,8 @@ export default defineMock({
292
308
  query: {},
293
309
  params: {},
294
310
  /**
295
- * refererQuery validates the query in the url of the page from which the request originated,
296
- * which makes it possible to modify parameters directly in the browser address bar to get
297
- * different mock data
311
+ * refererQuery 验证了请求来源页面 URL 中的查询参数,
312
+ * 这使得可以直接在浏览器地址栏中修改参数以获取不同的模拟数据。
298
313
  */
299
314
  refererQuery: {}
300
315
  },
@@ -571,7 +586,7 @@ export default defineMock({
571
586
  └── package.json
572
587
  ```
573
588
 
574
- 在该目录下,执行 `npm install` 安装依赖后,可执行 `npm start` 即可启动 mock server。
589
+ 在该目录下,执行 `npm install` 安装依赖后,执行 `npm start` 即可启动 mock server。
575
590
  默认端口为 `8080`。
576
591
  可通过 `localhost:8080/` 访问相关的 `mock` 接口。
577
592
 
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  baseMiddleware: () => baseMiddleware,
34
+ createDefineMock: () => createDefineMock,
34
35
  default: () => src_default,
35
36
  defineMock: () => defineMock,
36
37
  mockDevServerPlugin: () => mockDevServerPlugin,
@@ -38,7 +39,7 @@ __export(src_exports, {
38
39
  });
39
40
  module.exports = __toCommonJS(src_exports);
40
41
 
41
- // node_modules/.pnpm/tsup@6.6.3_typescript@4.9.5/node_modules/tsup/assets/cjs_shims.js
42
+ // node_modules/.pnpm/tsup@6.7.0_typescript@5.0.2/node_modules/tsup/assets/cjs_shims.js
42
43
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
43
44
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
44
45
 
@@ -53,7 +54,7 @@ var import_vite = require("vite");
53
54
 
54
55
  // package.json
55
56
  var name = "vite-plugin-mock-dev-server";
56
- var version = "1.0.5";
57
+ var version = "1.0.7";
57
58
 
58
59
  // src/esbuildPlugin.ts
59
60
  var import_promises = __toESM(require("fs/promises"), 1);
@@ -95,6 +96,41 @@ var jsonLoader = {
95
96
  });
96
97
  }
97
98
  };
99
+ var aliasPlugin = (alias) => {
100
+ return {
101
+ name: "alias-plugin",
102
+ setup(build3) {
103
+ build3.onResolve({ filter: /.*/ }, async ({ path: id }) => {
104
+ const matchedEntry = alias.find(({ find: find2 }) => matches(find2, id));
105
+ if (!matchedEntry) {
106
+ return null;
107
+ }
108
+ const { find, replacement } = matchedEntry;
109
+ const result = await build3.resolve(id.replace(find, replacement), {
110
+ kind: "import-statement",
111
+ resolveDir: replacement,
112
+ namespace: "file"
113
+ });
114
+ return {
115
+ path: result.path,
116
+ external: false
117
+ };
118
+ });
119
+ }
120
+ };
121
+ };
122
+ function matches(pattern, importee) {
123
+ if (pattern instanceof RegExp) {
124
+ return pattern.test(importee);
125
+ }
126
+ if (importee.length < pattern.length) {
127
+ return false;
128
+ }
129
+ if (importee === pattern) {
130
+ return true;
131
+ }
132
+ return importee.startsWith(`${pattern}/`);
133
+ }
98
134
 
99
135
  // src/utils.ts
100
136
  var import_node_fs = __toESM(require("fs"), 1);
@@ -174,7 +210,11 @@ async function generateMockServer(ctx, config, options) {
174
210
  const content = await generateMockEntryCode(process.cwd(), include, exclude);
175
211
  const mockEntry = import_node_path3.default.join(config.root, `mock-data-${Date.now()}.js`);
176
212
  await import_promises2.default.writeFile(mockEntry, content, "utf-8");
177
- const { code, deps } = await buildMockEntry(mockEntry, define);
213
+ const { code, deps } = await buildMockEntry(
214
+ mockEntry,
215
+ define,
216
+ config.resolve.alias
217
+ );
178
218
  const mockDeps = getMockDependencies(deps);
179
219
  await import_promises2.default.unlink(mockEntry);
180
220
  const outputList = [
@@ -288,7 +328,7 @@ const mockList = exporters.map((raw) => raw && raw.default
288
328
  export default transformMockData(mockList);
289
329
  `;
290
330
  }
291
- async function buildMockEntry(inputFile, define) {
331
+ async function buildMockEntry(inputFile, define, alias) {
292
332
  var _a;
293
333
  try {
294
334
  const result = await (0, import_esbuild.build)({
@@ -301,7 +341,7 @@ async function buildMockEntry(inputFile, define) {
301
341
  metafile: true,
302
342
  format: "esm",
303
343
  define,
304
- plugins: [externalizeDeps, json5Loader, jsonLoader]
344
+ plugins: [aliasPlugin(alias), externalizeDeps, json5Loader, jsonLoader]
305
345
  });
306
346
  return {
307
347
  code: result.outputFiles[0].text,
@@ -740,7 +780,7 @@ var _MockLoader = class extends import_node_events.default {
740
780
  metafile: true,
741
781
  format: isESM ? "esm" : "cjs",
742
782
  define: this.options.define,
743
- plugins: [externalizeDeps]
783
+ plugins: [aliasPlugin(this.options.alias), externalizeDeps]
744
784
  });
745
785
  return {
746
786
  code: result.outputFiles[0].text,
@@ -771,7 +811,8 @@ async function mockServerMiddleware(config, options, httpServer, ws) {
771
811
  const loader = new MockLoader({
772
812
  include,
773
813
  exclude,
774
- define
814
+ define,
815
+ alias: config.resolve.alias
775
816
  });
776
817
  await loader.load();
777
818
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
@@ -792,14 +833,7 @@ async function mockServerMiddleware(config, options, httpServer, ws) {
792
833
  function mockDevServerPlugin({
793
834
  prefix = [],
794
835
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
795
- exclude = [
796
- "**/node_modules/**",
797
- "**/test/**",
798
- "src/**",
799
- "**/.vscode/**",
800
- "**/.git/**",
801
- "**/dist/**"
802
- ],
836
+ exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
803
837
  reload = false,
804
838
  formidableOptions = {},
805
839
  build: build3 = false
@@ -880,12 +914,24 @@ function serverPlugin(pluginOptions) {
880
914
  function defineMock(config) {
881
915
  return config;
882
916
  }
917
+ function createDefineMock(transformer) {
918
+ const define = (config) => {
919
+ if (isArray(config)) {
920
+ config = config.map((item) => transformer(item) || item);
921
+ } else {
922
+ config = transformer(config) || config;
923
+ }
924
+ return config;
925
+ };
926
+ return define;
927
+ }
883
928
 
884
929
  // src/index.ts
885
930
  var src_default = mockDevServerPlugin;
886
931
  // Annotate the CommonJS export names for ESM import in node:
887
932
  0 && (module.exports = {
888
933
  baseMiddleware,
934
+ createDefineMock,
889
935
  defineMock,
890
936
  mockDevServerPlugin,
891
937
  transformMockData
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Connect, Plugin } from 'vite';
1
+ import { Connect, Plugin, ResolvedConfig } from 'vite';
2
2
  import http from 'node:http';
3
3
  import formidable from 'formidable';
4
4
  import EventEmitter from 'node:events';
@@ -172,12 +172,21 @@ declare function mockDevServerPlugin({ prefix, include, exclude, reload, formida
172
172
  */
173
173
  declare function defineMock(config: MockOptionsItem): MockOptionsItem;
174
174
  declare function defineMock(config: MockOptions): MockOptions;
175
+ /**
176
+ * 返回一个自定义的 defineMock 函数,用于支持对 mock config 的预处理。
177
+ *
178
+ * Return a custom defineMock function to support preprocessing of mock config.
179
+ *
180
+ * @param transformer preprocessing function
181
+ */
182
+ declare function createDefineMock(transformer: (mock: MockOptionsItem) => MockOptionsItem | void): typeof defineMock;
175
183
 
176
184
  interface MockLoaderOptions {
177
185
  cwd?: string;
178
186
  include: string[];
179
187
  exclude: string[];
180
188
  define: Record<string, any>;
189
+ alias: ResolvedConfig['resolve']['alias'];
181
190
  }
182
191
  /**
183
192
  * mock配置加载器
@@ -219,4 +228,4 @@ declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, pro
219
228
 
220
229
  declare function transformMockData(mockList: Map<string, MockOptionsItem | MockOptions> | (MockOptionsItem | MockOptions)[]): Record<string, MockOptions>;
221
230
 
222
- export { BaseMiddlewareOptions, FormidableFile, MockOptions, MockOptionsItem, MockServerPluginOptions, baseMiddleware, mockDevServerPlugin as default, defineMock, mockDevServerPlugin, transformMockData };
231
+ export { BaseMiddlewareOptions, FormidableFile, MockOptions, MockOptionsItem, MockServerPluginOptions, baseMiddleware, createDefineMock, mockDevServerPlugin as default, defineMock, mockDevServerPlugin, transformMockData };
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { createFilter, normalizePath } from "vite";
9
9
 
10
10
  // package.json
11
11
  var name = "vite-plugin-mock-dev-server";
12
- var version = "1.0.5";
12
+ var version = "1.0.7";
13
13
 
14
14
  // src/esbuildPlugin.ts
15
15
  import fsp from "fs/promises";
@@ -51,6 +51,41 @@ var jsonLoader = {
51
51
  });
52
52
  }
53
53
  };
54
+ var aliasPlugin = (alias) => {
55
+ return {
56
+ name: "alias-plugin",
57
+ setup(build3) {
58
+ build3.onResolve({ filter: /.*/ }, async ({ path: id }) => {
59
+ const matchedEntry = alias.find(({ find: find2 }) => matches(find2, id));
60
+ if (!matchedEntry) {
61
+ return null;
62
+ }
63
+ const { find, replacement } = matchedEntry;
64
+ const result = await build3.resolve(id.replace(find, replacement), {
65
+ kind: "import-statement",
66
+ resolveDir: replacement,
67
+ namespace: "file"
68
+ });
69
+ return {
70
+ path: result.path,
71
+ external: false
72
+ };
73
+ });
74
+ }
75
+ };
76
+ };
77
+ function matches(pattern, importee) {
78
+ if (pattern instanceof RegExp) {
79
+ return pattern.test(importee);
80
+ }
81
+ if (importee.length < pattern.length) {
82
+ return false;
83
+ }
84
+ if (importee === pattern) {
85
+ return true;
86
+ }
87
+ return importee.startsWith(`${pattern}/`);
88
+ }
54
89
 
55
90
  // src/utils.ts
56
91
  import fs from "fs";
@@ -130,7 +165,11 @@ async function generateMockServer(ctx, config, options) {
130
165
  const content = await generateMockEntryCode(process.cwd(), include, exclude);
131
166
  const mockEntry = path3.join(config.root, `mock-data-${Date.now()}.js`);
132
167
  await fsp2.writeFile(mockEntry, content, "utf-8");
133
- const { code, deps } = await buildMockEntry(mockEntry, define);
168
+ const { code, deps } = await buildMockEntry(
169
+ mockEntry,
170
+ define,
171
+ config.resolve.alias
172
+ );
134
173
  const mockDeps = getMockDependencies(deps);
135
174
  await fsp2.unlink(mockEntry);
136
175
  const outputList = [
@@ -244,7 +283,7 @@ const mockList = exporters.map((raw) => raw && raw.default
244
283
  export default transformMockData(mockList);
245
284
  `;
246
285
  }
247
- async function buildMockEntry(inputFile, define) {
286
+ async function buildMockEntry(inputFile, define, alias) {
248
287
  var _a;
249
288
  try {
250
289
  const result = await build({
@@ -257,7 +296,7 @@ async function buildMockEntry(inputFile, define) {
257
296
  metafile: true,
258
297
  format: "esm",
259
298
  define,
260
- plugins: [externalizeDeps, json5Loader, jsonLoader]
299
+ plugins: [aliasPlugin(alias), externalizeDeps, json5Loader, jsonLoader]
261
300
  });
262
301
  return {
263
302
  code: result.outputFiles[0].text,
@@ -696,7 +735,7 @@ var _MockLoader = class extends EventEmitter {
696
735
  metafile: true,
697
736
  format: isESM ? "esm" : "cjs",
698
737
  define: this.options.define,
699
- plugins: [externalizeDeps]
738
+ plugins: [aliasPlugin(this.options.alias), externalizeDeps]
700
739
  });
701
740
  return {
702
741
  code: result.outputFiles[0].text,
@@ -727,7 +766,8 @@ async function mockServerMiddleware(config, options, httpServer, ws) {
727
766
  const loader = new MockLoader({
728
767
  include,
729
768
  exclude,
730
- define
769
+ define,
770
+ alias: config.resolve.alias
731
771
  });
732
772
  await loader.load();
733
773
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
@@ -748,14 +788,7 @@ async function mockServerMiddleware(config, options, httpServer, ws) {
748
788
  function mockDevServerPlugin({
749
789
  prefix = [],
750
790
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
751
- exclude = [
752
- "**/node_modules/**",
753
- "**/test/**",
754
- "src/**",
755
- "**/.vscode/**",
756
- "**/.git/**",
757
- "**/dist/**"
758
- ],
791
+ exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
759
792
  reload = false,
760
793
  formidableOptions = {},
761
794
  build: build3 = false
@@ -836,11 +869,23 @@ function serverPlugin(pluginOptions) {
836
869
  function defineMock(config) {
837
870
  return config;
838
871
  }
872
+ function createDefineMock(transformer) {
873
+ const define = (config) => {
874
+ if (isArray(config)) {
875
+ config = config.map((item) => transformer(item) || item);
876
+ } else {
877
+ config = transformer(config) || config;
878
+ }
879
+ return config;
880
+ };
881
+ return define;
882
+ }
839
883
 
840
884
  // src/index.ts
841
885
  var src_default = mockDevServerPlugin;
842
886
  export {
843
887
  baseMiddleware,
888
+ createDefineMock,
844
889
  src_default as default,
845
890
  defineMock,
846
891
  mockDevServerPlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-mock-dev-server",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "keywords": [
5
5
  "vite",
6
6
  "plugin",
@@ -33,7 +33,7 @@
33
33
  "chokidar": "^3.5.3",
34
34
  "co-body": "^6.1.0",
35
35
  "debug": "^4.3.4",
36
- "esbuild": "^0.17.11",
36
+ "esbuild": "^0.17.12",
37
37
  "fast-glob": "^3.2.12",
38
38
  "formidable": "^2.1.1",
39
39
  "http-status": "^1.6.2",
@@ -43,22 +43,22 @@
43
43
  "picocolors": "^1.0.0"
44
44
  },
45
45
  "devDependencies": {
46
- "@pengzhanbo/eslint-config-ts": "^0.3.2",
47
- "@pengzhanbo/prettier-config": "^0.3.2",
46
+ "@pengzhanbo/eslint-config-ts": "^0.3.4",
47
+ "@pengzhanbo/prettier-config": "^0.3.4",
48
48
  "@types/co-body": "^6.1.0",
49
49
  "@types/debug": "^4.1.7",
50
50
  "@types/formidable": "^2.0.5",
51
51
  "@types/is-core-module": "^2.2.0",
52
- "@types/node": "^18.14.6",
52
+ "@types/node": "^18.15.5",
53
53
  "bumpp": "^9.0.0",
54
54
  "conventional-changelog-cli": "^2.2.2",
55
- "eslint": "^8.35.0",
55
+ "eslint": "^8.36.0",
56
56
  "mockjs": "^1.1.0",
57
- "prettier": "^2.8.4",
58
- "tsup": "^6.6.3",
59
- "typescript": "^4.9.5",
60
- "vite": "^4.1.4",
61
- "vitepress": "1.0.0-alpha.49",
57
+ "prettier": "^2.8.6",
58
+ "tsup": "^6.7.0",
59
+ "typescript": "^5.0.2",
60
+ "vite": "^4.2.1",
61
+ "vitepress": "1.0.0-alpha.61",
62
62
  "vue": "^3.2.47"
63
63
  },
64
64
  "peerDependencies": {