Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"picomatch",
"proxied",
"referer",
"rolldown",
"tsdown"
],
"typescript.tsdk": "node_modules/typescript/lib",
Expand Down
24 changes: 20 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

- ⚡️ Lightweight, Flexible, Fast.
- 🧲 Not injection-based, non-intrusive to client code.
- 💡 ESModule/commonjs.
- 💡 Pure ESModule.
- 🦾 Typescript.
- 🔥 HMR
- 🏷 Support `.[cm]?js` / `.ts` / `.json` / `.json5`.
Expand All @@ -52,6 +52,14 @@ See the [documentation](https://vite-plugin-mock-dev-server.netlify.app/) for mo

[![Netlify Status](https://api.netlify.com/api/v1/badges/9ccda610-2c6a-4cd0-aeaa-a8932f2b477c/deploy-status)](https://app.netlify.com/sites/vite-plugin-mock-dev-server/deploys)

> [!IMPORTANT]
> The plugin no longer supports `CommonJS` imports. Please use `ESModule` to import the plugin.

----

> [!IMPORTANT]
> The current document is for the `v2` version of the plugin. If you are using the `v1` version, please refer to the [Migration Guide](https://vite-plugin-mock-dev-server.netlify.app/guide/migrate-v2).

## Install

``` sh
Expand Down Expand Up @@ -100,7 +108,7 @@ By default, write mock data in the `mock` directory of your project's root direc
import { defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock({
url: '/api/test',
url: '/api/user/:id',
body: { a: 1, b: 2 }
})
```
Expand Down Expand Up @@ -205,18 +213,26 @@ export default defineMock({

Configure the matching context for `include` and `exclude`.

### dir

- **Type:** `string`
- **Default:** `'mock'`
- **Details:**

Configure the directory to read mock files.

### include

- **Type:** `string | string[]`
- **Default:** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` (Relative to the root directory)
- **Default:** `['**/*.mock.{js,ts,cjs,mjs,json,json5}']`
- **Details:**

Configure to read mock files, which can be a directory, glob, or an array.

### exclude

- **Type:** `string | string[]`
- **Default:** `['**/node_modules/**','**/.vscode/**','**/.git/**']`
- **Default:** `['**/node_modules/**']`
- **Details:**

When reading mock files for configuration, the files that need to be excluded can be a directory, glob, or array.
Expand Down
24 changes: 20 additions & 4 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

- ⚡️ 轻量,灵活,快速
- 🧲 非注入式,对客户端代码无侵入
- 💡 ESModule/commonjs
- 💡 ESModule
- 🦾 Typescript
- 🔥 热更新
- 🏷 支持 `.[cm]?js` / `.ts` / `.json` / `.json5` 编写 mock 数据
Expand All @@ -53,6 +53,14 @@

[![Netlify Status](https://api.netlify.com/api/v1/badges/9ccda610-2c6a-4cd0-aeaa-a8932f2b477c/deploy-status)](https://app.netlify.com/sites/vite-plugin-mock-dev-server/deploys)

> [!IMPORTANT]
> 插件不再支持 `CommonJS` 导入使用,请使用 `ESModule` 导入插件

----

> [!IMPORTANT]
> 当前文档为插件的 `v2` 版本,如果您正在使用 `v1` 版本,请参考 [迁移文档](https://vite-plugin-mock-dev-server.netlify.app/zh/guide/migrate-v2)

## 安装

```sh
Expand Down Expand Up @@ -101,7 +109,7 @@ export default defineConfig({
import { defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock({
url: '/api/test',
url: '/api/user/:id',
body: { a: 1, b: 2 }
})
```
Expand Down Expand Up @@ -205,18 +213,26 @@ export default defineMock({

配置 `include` 和 `exclude` 的匹配上下文

### dir

- **类型:** `string`
- **默认值:** `'mock'`
- **详情:**

配置mock数据的目录,相对于 `cwd`

### include

- **类型:** `string | string[]`
- **默认值:** `['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']` (相对于根目录)
- **默认值:** `['**/*.mock.{js,ts,cjs,mjs,json,json5}']`
- **详情:**

配置读取 mock文件,可以是一个 目录,glob,或者一个数组

### exclude

- **类型:** `string | string[]`
- **默认值:** `['**/node_modules/**', '**/.vscode/**', '**/.git/**']`
- **默认值:** `['**/node_modules/**']`
- **详情:**

配置读取 mock文件时,需要排除的文件, 可以是一个 目录、glob、或者一个数组
Expand Down
2 changes: 1 addition & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const vitepressConfig: UserConfig<DefaultTheme.Config> = defineConfig({
},
vite: {
plugins: [
groupIconVitePlugin(),
groupIconVitePlugin() as any,
prod && llmstxt({
workDir: 'en',
ignoreFiles: ['index.md'],
Expand Down
1 change: 1 addition & 0 deletions docs/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
{ text: 'Introduce', link: 'introduce' },
{ text: 'Install', link: 'install' },
{ text: 'Usage', link: 'usage' },
{ text: 'Migrate from v1.0', link: 'migrate-v2' },
],
},
{
Expand Down
8 changes: 4 additions & 4 deletions docs/en/examples/static.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Static resource service

Retrieve the file path from the request through dynamic route matching using `:filepath(.*)`, obtain the file path from the request, return it as a file stream in the body, and set the correct `Content-Type` in the headers.
Retrieve the file path from the request through dynamic route matching using `*filepath`, obtain the file path from the request, return it as a file stream in the body, and set the correct `Content-Type` in the headers.

```ts
import { createReadStream } from 'node:fs'
Expand All @@ -12,18 +12,18 @@ import { defineMock } from 'vite-plugin-mock-dev-server'
const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default defineMock({
url: '/mockData/:filepath(.*)',
url: '/mock-static/*filepath',
method: 'GET',
headers(request) {
const { filepath } = request.params
const filepath = request.params.filepath.join('/')
const filename = path.basename(filepath)
return {
'Content-Type': mime.lookup(filename) || 'text/plain',
}
},
body(request) {
const { filepath } = request.params
return createReadStream(path.join(__dirname, 'mockData', filepath))
return createReadStream(path.join(__dirname, 'mock-static', filepath))
},
})
```
37 changes: 37 additions & 0 deletions docs/en/guide/migrate-v2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Migrate from v1.x

## Pure ESM Support

The plugin no longer provides `CommonJS` code exports. Please use the ESM mode to import the plugin.

```ts
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server' // ✔️
```

```js
const { mockDevServerPlugin } = require('vite-plugin-mock-dev-server') // ✖️ // [!code error]
```

## Rolldown & Esbuild Support

The plugin now automatically selects different compilers to process mock files based on different versions of Vite.

For the `vite@npm:rolldown-vite@latest` version, `rolldown` is used as the compiler.

## path-to-regexp Upgraded from v6 to v8

The plugin now uses [`path-to-regexp@v8`](https://github.com/pillarjs/path-to-regexp#readme) as the path matching engine.

Please refer to the [official documentation](https://github.com/pillarjs/path-to-regexp#unexpected--or-) for adaptation and upgrade.

## Plugin Configuration

Added a new `dir` configuration option to specify the directory for mock files, relative to `cwd`. The matching context for `include` and `exclude` is `cwd + dir`.

::: details Why was this adjustment made?

The plugin uses `chokidar` to monitor changes in mock files, starting the matching from the `cwd` directory by default. The search scope may be too large for medium to large projects,

which could lead to unnecessary performance overhead. Therefore, the `dir` configuration option has been added to further narrow down the search scope.

:::
20 changes: 16 additions & 4 deletions docs/en/guide/plugin-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
`type: MockServerPluginOptions`

``` ts
import process from 'node:process'
import { defineConfig } from 'vite'
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'

Expand All @@ -11,7 +12,9 @@ export default defineConfig({
mockDevServerPlugin({
prefix: [],
wsPrefix: [],
include: ['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}'],
cwd: process.cwd(),
dir: 'mock',
include: ['**/*.mock.{js,ts,cjs,mjs,json,json5}'],
exclude: '',
log: 'info',
reload: false,
Expand All @@ -31,6 +34,8 @@ export default defineConfig({
interface MockServerPluginOptions {
prefix?: string | string[]
wsPrefix?: string | string[]
cwd?: string
dir?: string
include?: string | string[]
exclude?: string | string[]
reload?: boolean
Expand Down Expand Up @@ -74,11 +79,18 @@ This conflict is not a problem with Vite or the plugin itself; it is a reasonabl

Configure the matching context for `include` and `exclude`.

## dir

- **Type**: `string`
- **Default**: `'mock'`

The directory for configuring mock data, relative to `cwd`.

## include

**Type**: `string | string[]`

- **Default**:relative to [`cwd`](#cwd)
- **Default**:relative to [`cwd`](#cwd) + [`dir`](#dir)

```ts
['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}']
Expand All @@ -90,10 +102,10 @@ Configure the reading of mock files, which can be a directory, a glob pattern, o

- **Type**: `string | string[]`

- **Default**:relative to [`cwd`](#cwd)
- **Default**:relative to [`cwd`](#cwd) + [`dir`](#dir)

```ts
['**/node_modules/**', '**/test/**', '**/cypress/**', 'src/**', '**/.vscode/**', '**/.git/**', '**/dist/**']
['**/node_modules/**']
```

Specifies the files to be excluded when reading mock files. It can be a directory, glob pattern, or an array.
Expand Down
5 changes: 3 additions & 2 deletions docs/zh/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
{ text: '介绍', link: 'introduce' },
{ text: '安装', link: 'install' },
{ text: '使用', link: 'usage' },
{ text: '从 v1.x 迁移', link: 'migrate-v2' },
],
},
{
Expand All @@ -125,8 +126,8 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
{
text: '配置',
items: [
{ text: 'pluginConfig', link: 'plugin-config' },
{ text: 'mockConfig', link: 'mock-config' },
{ text: '插件配置', link: 'plugin-config' },
{ text: 'mock 配置', link: 'mock-config' },
],
},
{
Expand Down
8 changes: 4 additions & 4 deletions docs/zh/examples/static.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 静态资源服务

通过 动态路由匹配,获取请求的文件路径 `:filepath(.*)`, 获取请求中的文件路径,
通过 动态路由匹配,获取请求的文件路径 `*filepath`, 获取请求中的文件路径,
在 `body` 中以文件流的方式返回,并在 `headers` 中设置正确的 `Content-Type`。

```ts
Expand All @@ -13,18 +13,18 @@ import { defineMock } from 'vite-plugin-mock-dev-server'
const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default defineMock({
url: '/mockData/:filepath(.*)',
url: '/mock-static/*filepath',
method: 'GET',
headers(request) {
const { filepath } = request.params
const filepath = request.params.filepath.join('/')
const filename = path.basename(filepath)
return {
'Content-Type': mime.lookup(filename) || 'text/plain',
}
},
body(request) {
const { filepath } = request.params
return createReadStream(path.join(__dirname, 'mockData', filepath))
return createReadStream(path.join(__dirname, 'mock-static', filepath))
},
})
```
33 changes: 33 additions & 0 deletions docs/zh/guide/migrate-v2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# 从 v1.x 迁移

## 纯 ESM 支持

插件不再提供 `CommonJS` 代码导出,请使用 ESM 模式导入插件。

```ts
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server' // ✔️
```

```js
const { mockDevServerPlugin } = require('vite-plugin-mock-dev-server') // ✖️ // [!code error]
```

## Rolldown & Esbuild 支持

插件现在会根据 Vite 不同版本,自动选择不同的编译器处理 mock 文件。

对于 `vite@npm:rolldown-vite@latest` 版本,使用 `rolldown` 作为编译器。

## path-to-regexp 从 v6 升级到 v8

插件现在使用 [`path-to-regexp@v8`](https://github.com/pillarjs/path-to-regexp#readme) 作为路径匹配引擎。
请参考 [官方文档](https://github.com/pillarjs/path-to-regexp#unexpected--or-) 进行适配升级。

## 插件配置

新增 `dir` 配置项,用于配置 mock 文件的目录,相对于 `cwd`。`include` 和 `exclude` 的匹配上下文为 `cwd + dir`

::: details 为什么做出此调整?
插件使用 `chokidar` 监听 mock 文件变更,默认从 `cwd` 目录开始匹配,其查找范围对于中大型项目可能会很大,
这可能带来不必要的性能开销。因此新增 `dir` 配置项进一步缩小查找范围。
:::
2 changes: 1 addition & 1 deletion docs/zh/guide/mock-config.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# mockConfig
# mock 配置

`type: MockOptionsItem | MockOptionsItem[]`

Expand Down
Loading