From 31ef1517271a6eb2266debcceebf590c5a906680 Mon Sep 17 00:00:00 2001 From: "chuyuan.du" Date: Thu, 25 Jul 2024 13:17:27 +0800 Subject: [PATCH 1/3] =?UTF-8?q?plugin=20=E6=89=A7=E8=A1=8C=E6=96=87?= =?UTF-8?q?=E4=BB=B6=20include=E5=92=8C=20exclude=E7=9A=84cwd=E4=B8=8Evite?= =?UTF-8?q?=20config=E4=B8=AD=E4=BF=9D=E6=8C=81=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/mockMiddleware.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mockMiddleware.ts b/src/mockMiddleware.ts index 5074970..502b8a7 100644 --- a/src/mockMiddleware.ts +++ b/src/mockMiddleware.ts @@ -34,6 +34,7 @@ export function mockServerMiddleware( exclude: toArray(options.exclude), define: viteDefine(config), alias: config.resolve.alias, + cwd: config.root, }) loader.load() From b142814a32c2efc11a41855656da225448314682 Mon Sep 17 00:00:00 2001 From: pengzhanbo Date: Thu, 25 Jul 2024 16:14:39 +0800 Subject: [PATCH 2/3] feat: add plugin options `cwd` --- src/MockLoader.ts | 6 +++--- src/build.ts | 5 +++-- src/compiler.ts | 19 +++++++++++++------ src/mockMiddleware.ts | 2 +- src/plugin.ts | 3 +++ src/types.ts | 10 ++++++++++ 6 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/MockLoader.ts b/src/MockLoader.ts index 5189df1..2f8c41f 100644 --- a/src/MockLoader.ts +++ b/src/MockLoader.ts @@ -201,12 +201,12 @@ export class MockLoader extends EventEmitter { try { const raw - = (await loadFromCode( + = (await loadFromCode({ filepath, code, isESM, - this.cwd, - )) || {} + cwd: this.cwd, + })) || {} let mockConfig: MockHttpItem | MockWebsocketItem | MockOptions if (hasOwn(raw, 'default')) { diff --git a/src/build.ts b/src/build.ts index 18cdb5a..41fd6a2 100644 --- a/src/build.ts +++ b/src/build.ts @@ -35,6 +35,7 @@ export async function generateMockServer( const include = toArray(options.include) const exclude = toArray(options.exclude) const define = viteDefine(config) + const cwd = options.cwd || process.cwd() const { httpProxies } = ensureProxies(config.server.proxy || {}) httpProxies.push(...toArray(options.prefix)) @@ -50,8 +51,8 @@ export async function generateMockServer( const outputDir = (options.build as ServerBuildOption).dist! - const content = await generateMockEntryCode(process.cwd(), include, exclude) - const mockEntry = path.join(config.root, `mock-data-${Date.now()}.js`) + const content = await generateMockEntryCode(cwd, include, exclude) + const mockEntry = path.join(cwd, `mock-data-${Date.now()}.js`) await fsp.writeFile(mockEntry, content, 'utf-8') const { code, deps } = await transformWithEsbuild(mockEntry, { define, diff --git a/src/compiler.ts b/src/compiler.ts index 1c9b13f..29dd276 100644 --- a/src/compiler.ts +++ b/src/compiler.ts @@ -134,12 +134,19 @@ export async function transformWithEsbuild( const _dirname = getDirname(import.meta.url) const _require = createRequire(_dirname) -export async function loadFromCode( - filepath: string, - code: string, - isESM: boolean, - cwd: string, -): Promise<{ [key: string]: T }> { +interface LoadFromCodeOptions { + filepath: string + code: string + isESM: boolean + cwd: string +} + +export async function loadFromCode({ + filepath, + code, + isESM, + cwd, +}: LoadFromCodeOptions): Promise<{ [key: string]: T }> { if (isESM) { const fileBase = `${filepath}.timestamp-${Date.now()}` const fileNameTmp = `${fileBase}.mjs` diff --git a/src/mockMiddleware.ts b/src/mockMiddleware.ts index 502b8a7..4ccec3b 100644 --- a/src/mockMiddleware.ts +++ b/src/mockMiddleware.ts @@ -30,11 +30,11 @@ export function mockServerMiddleware( * 并注入 vite `define` / `alias` */ const loader = new MockLoader({ + cwd: options.cwd, include: toArray(options.include), exclude: toArray(options.exclude), define: viteDefine(config), alias: config.resolve.alias, - cwd: config.root, }) loader.load() diff --git a/src/plugin.ts b/src/plugin.ts index 7ef3d23..a343e73 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,3 +1,4 @@ +import process from 'node:process' import { toArray } from '@pengzhanbo/utils' import type { Plugin, ResolvedConfig } from 'vite' import { generateMockServer } from './build' @@ -8,6 +9,7 @@ import type { MockServerPluginOptions } from './types' export function mockDevServerPlugin({ prefix = [], wsPrefix = [], + cwd = process.cwd(), include = ['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}'], exclude = ['**/node_modules/**', '**/.vscode/**', '**/.git/**'], reload = false, @@ -22,6 +24,7 @@ export function mockDevServerPlugin({ const pluginOptions: Required = { prefix, wsPrefix, + cwd, include, exclude, reload, diff --git a/src/types.ts b/src/types.ts index aa251fa..e58fe45 100644 --- a/src/types.ts +++ b/src/types.ts @@ -39,6 +39,16 @@ export interface MockServerPluginOptions { * @example ['/socket.io'] */ wsPrefix?: string | string[] + + /** + * Configure the matching context for `include` and `exclude`. + * + * 配置 `include` 和 `exclude` 的匹配上下文 + * + * @default process.cwd() + */ + cwd?: string + /** * glob string matching mock includes files * From 3bea85229e5381722e286a4ec92f341087675f29 Mon Sep 17 00:00:00 2001 From: pengzhanbo Date: Thu, 25 Jul 2024 16:14:52 +0800 Subject: [PATCH 3/3] docs: update docs --- README.md | 8 ++++++++ README.zh-CN.md | 8 ++++++++ docs/en/guide/plugin-config.md | 12 ++++++++++-- docs/guide/plugin-config.md | 12 ++++++++++-- 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index dddde03..aaa9c57 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,14 @@ export default defineConfig({ > Different from using `viteConfig.server.proxy` by default for http mock, `websocket mock` does not use the ws-related configuration in `viteConfig.server.proxy`. Also, rules configured in `wsPrefix` cannot be configured simultaneously in `viteConfig.server.proxy`, as it will cause conflicts when starting the vite server because multiple instances of WebSocketServer cannot be implemented for the same request. > This conflict is neither a problem with Vite nor with the plugin; it belongs to a reasonable error type. When switching between WebSocket Mock and WebSocket Proxy, please pay attention to avoid duplicate configurations that may cause conflicts. +- `option.cwd` + + **Type:** `string` + + Configure the matching context for `include` and `exclude`. + + **Default:** `process.cwd()` + - `option.include` **Type:** `string | string[]` diff --git a/README.zh-CN.md b/README.zh-CN.md index 9282e80..38e67d5 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -151,6 +151,14 @@ export default defineConfig({ > 与 http mock 默认使用 `viteConfig.server.proxy` 不同的是,`websocket mock` 不会使用 `viteConfig.server.proxy` 中的 ws 相关的配置,且配置在 `wsPrefix` 中的规则,不能同时配置在 `viteConfig.server.proxy`中,因为会导致在 vite 在启动服务时产生冲突,因为不能对同一个请求实现多个的 `WebSocketServer`实例。 > 该冲突既不是 `vite` 的问题,也不是插件的问题,这属于合理的错误类型。在进行 `WebSocket Mock`和 `WebSocket Proxy` 切换时,请注意配置不要出现重复导致冲突。 +- `option.cwd` + + **类型:** `string` + + 配置 `include` 和 `exclude` 的匹配上下文 + + **默认值:** `process.cwd()` + - `option.include` **类型:** `string | string[]` diff --git a/docs/en/guide/plugin-config.md b/docs/en/guide/plugin-config.md index 97bf966..10fad68 100644 --- a/docs/en/guide/plugin-config.md +++ b/docs/en/guide/plugin-config.md @@ -66,12 +66,20 @@ Unlike the default behavior of using `viteConfig.server.proxy` for HTTP mocks, W This conflict is not a problem with Vite or the plugin itself; it is a reasonable type of error. When switching between WebSocket Mock and WebSocket Proxy, please ensure that the configuration does not contain duplicates that could cause conflicts. +## cwd + +**Type**: `string` + +**Default**: `process.cwd()` + +Configure the matching context for `include` and `exclude`. + ## include **Type**: `string | string[]` **Default**: -`['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` relative to root +`['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` relative to [`cwd`](#cwd) Configure the reading of mock files, which can be a directory, a glob pattern, or an array. @@ -80,7 +88,7 @@ Configure the reading of mock files, which can be a directory, a glob pattern, o **Type**: `string | string[]` **Default**: -`['**/node_modules/**','**/test/**','**/cypress/**','src/**','**/.vscode/**','**/.git/**','**/dist/**']` +`['**/node_modules/**','**/test/**','**/cypress/**','src/**','**/.vscode/**','**/.git/**','**/dist/**']` relative to [`cwd`](#cwd) Specifies the files to be excluded when reading mock files. It can be a directory, glob pattern, or an array. diff --git a/docs/guide/plugin-config.md b/docs/guide/plugin-config.md index 7077458..06d34ee 100644 --- a/docs/guide/plugin-config.md +++ b/docs/guide/plugin-config.md @@ -70,12 +70,20 @@ interface MockServerPluginOptions { 该冲突既不是 `vite` 的问题,也不是插件的问题,这属于合理的错误类型。在进行 `WebSocket Mock`和 `WebSocket Proxy` 切换时,请注意配置不要出现重复导致冲突。 +## cwd + +**类型**: `string` + +**默认值**: `process.cwd()` + +配置 `include` 和 `exclude` 的匹配上下文 + ## include **类型**: `string | string[]` **默认值**: -`['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` 相对于根目录 +`['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` 相对于 [`cwd`](#cwd) 配置读取 mock文件,可以是一个 目录,glob,或者一个数组 @@ -84,7 +92,7 @@ interface MockServerPluginOptions { **类型**: `string | string[]` **默认值**: -`['**/node_modules/**','**/test/**','**/cypress/**','src/**','**/.vscode/**','**/.git/**','**/dist/**']` +`['**/node_modules/**','**/test/**','**/cypress/**','src/**','**/.vscode/**','**/.git/**','**/dist/**']` 相对于 [`cwd`](#cwd) 配置读取 mock文件时,需要排除的文件, 可以是一个 目录、glob、或者一个数组