Skip to content

Commit

Permalink
feat: add plugin options cwd (#83)
Browse files Browse the repository at this point in the history
* feat: add plugin options `cwd`

* docs: update docs

---------

Co-authored-by: pengzhanbo <[email protected]>
  • Loading branch information
chuyuandu and pengzhanbo authored Jul 25, 2024
1 parent f438659 commit 43cf97b
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 15 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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[]`
Expand Down
8 changes: 8 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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[]`
Expand Down
12 changes: 10 additions & 2 deletions docs/en/guide/plugin-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.

Expand Down
12 changes: 10 additions & 2 deletions docs/guide/plugin-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,或者一个数组

Expand All @@ -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、或者一个数组

Expand Down
6 changes: 3 additions & 3 deletions src/MockLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,12 @@ export class MockLoader extends EventEmitter {

try {
const raw
= (await loadFromCode<MockHttpItem | MockWebsocketItem | MockOptions>(
= (await loadFromCode<MockHttpItem | MockWebsocketItem | MockOptions>({
filepath,
code,
isESM,
this.cwd,
)) || {}
cwd: this.cwd,
})) || {}
let mockConfig: MockHttpItem | MockWebsocketItem | MockOptions

if (hasOwn(raw, 'default')) {
Expand Down
5 changes: 3 additions & 2 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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,
Expand Down
19 changes: 13 additions & 6 deletions src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,19 @@ export async function transformWithEsbuild(
const _dirname = getDirname(import.meta.url)
const _require = createRequire(_dirname)

export async function loadFromCode<T = any>(
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<T = any>({
filepath,
code,
isESM,
cwd,
}: LoadFromCodeOptions): Promise<{ [key: string]: T }> {
if (isESM) {
const fileBase = `${filepath}.timestamp-${Date.now()}`
const fileNameTmp = `${fileBase}.mjs`
Expand Down
1 change: 1 addition & 0 deletions src/mockMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export function mockServerMiddleware(
* 并注入 vite `define` / `alias`
*/
const loader = new MockLoader({
cwd: options.cwd,
include: toArray(options.include),
exclude: toArray(options.exclude),
define: viteDefine(config),
Expand Down
3 changes: 3 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import process from 'node:process'
import { toArray } from '@pengzhanbo/utils'
import type { Plugin, ResolvedConfig } from 'vite'
import { generateMockServer } from './build'
Expand All @@ -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,
Expand All @@ -22,6 +24,7 @@ export function mockDevServerPlugin({
const pluginOptions: Required<MockServerPluginOptions> = {
prefix,
wsPrefix,
cwd,
include,
exclude,
reload,
Expand Down
10 changes: 10 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down

0 comments on commit 43cf97b

Please sign in to comment.