Vite-plugin-fake-server
A fake server plugin for Vite. Live Demo
Features
- Simple to use, configuration file driven.
- No reliance on fake library —— you can use @faker-js/faker or mockjs and so on.
- ESM first.
- Support
ts
, js
, mjs
files. - Support multiple response methods —— responseType.
- Support custom response headers.
- Support development and production environments.
- Support exporting independent deployment services —— build option.
- Friendly type prompt —— defineFakeRoute.
- Intercept XHR and Fetch request - XHook.
Install
npm install --save-dev vite-plugin-fake-server
Usage
Configure plugins in the configuration file of Vite, such as vite.config.ts
:
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { vitePluginFakeServer } from "vite-plugin-fake-server";
export default defineConfig({
plugins: [
react(),
vitePluginFakeServer(),
],
});
By default, it is only valid in the development environment (enableDev = true
), and monitors in real time (watch = true
) all ts
, js
, mjs
files in the mock folder under the current project. When the browser has For the real requested link, the terminal will automatically print the requested URL (Vite's logLevel = "info"
and clearScreen = true
).
Examples
For case details, please click this link to view packages/playground/react-sample/src
The most recommended way is to use a TypeScript file so you can use the defineFakeRoute
function to get good code hints.
The defineFakeRoute function parameters require the user to enter the route type as follows:
export interface FakeRoute {
url: string;
method?: HttpMethodType;
timeout?: number;
statusCode?: number;
statusText?: string;
headers?: OutgoingHttpHeaders;
response?: (processedRequest: ProcessedRequest, req: IncomingMessage, res: ServerResponse) => any;
rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
}
export type FakeRouteConfig = FakeRoute[] | FakeRoute;
export function defineFakeRoute(config: FakeRouteConfig) {
return config;
}
It should be noted that this way of introduction will cause vite build
to fail.
import { defineFakeRoute } from "vite-plugin-fake-server";
In .ts
file
import { faker } from "@faker-js/faker";
import Mock from "mockjs";
import { defineFakeRoute } from "vite-plugin-fake-server/client";
const adminUserTemplate = {
id: "@guid",
username: "@first",
email: "@email",
avatar: '@image("200x200")',
role: "admin",
};
const adminUserInfo = Mock.mock(adminUserTemplate);
export default defineFakeRoute([
{
url: "/mock/get-user-info",
response: () => {
return adminUserInfo;
},
},
{
url: "/fake/get-user-info",
response: () => {
return {
id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate(),
email: faker.internet.email(),
firstName: faker.person.firstName(),
lastName: faker.person.lastName(),
sex: faker.person.sexType(),
role: "admin",
};
},
},
]);
In .js
file
export default [
{
url: "/mock/esm",
response: ({ query }) => {
return { format: "ESM", query };
},
},
{
url: "/mock/response-text",
response: (_, req) => {
return req.headers["content-type"];
},
},
{
url: "/mock/post",
method: "POST",
response: ({ body }) => {
return { ...body, timestamp: Date.now() };
},
},
];
In .mjs
file
export default {
url: "/mock/mjs",
method: "POST",
statusCode: 200,
statusText: "OK",
response: () => {
return { format: "ESM" };
},
};
API
vitePluginFakeServer(options?)
options
include
Type: string
Default: "mock"
Set the folder where the mock/fake ts
, js
, mjs
files is stored.
exclude
Type: string[]
Default: []
Exclude files in the include
directory.
document: https://github.com/mrmlnc/fast-glob#ignore
watch
Type: boolean
Default: true
Set whether to listen to include
files.
extensions
Type: string[]
Default: ["ts", "js", "mjs"]
Set the mock files extensions.
timeout
Type: number
Default: undefined
Set default response delay time.
basename
Type: string
Default: ""
Set the root address of the request URL.
Type: OutgoingHttpHeaders
Default: {}
Set default headers for responses.
enableDev
Type: boolean
Default: true
Set up the service simulator in the development environment.
Powered by Connect technology.
enableProd
Type: boolean
Default: false
Set up the service simulator in the production environment.
Powered by XHook technology.
⚠️ The node module cannot be used in the mock file, otherwise the production environment will fail.As an alternative to keep consistent with the development environment, you can build a standalone deployment server, see build option.
Compared with the development environment, the API interface defined in the production environment does not have a rawResponse
function. The response function does not have the second parameter request
and the third parameter response
.
export interface FakeRoute {
url: string;
method?: HttpMethodType;
timeout?: number;
statusCode?: number;
statusText?: string;
headers?: OutgoingHttpHeaders;
response?: (processedRequest: ProcessedRequest) => any;
}
build
Type: boolean | ServerBuildOptions
Default: false
Set whether to export a independently deployable fake service(only valid in build mode).
interface ServerBuildOptions {
port?: number;
outDir?: string;
}
Shared Options
In order to maintain logs and screen clearing strategies consistent with Vite style on the terminal, the vite-plugin-fake-server plugin will automatically read the following three parameters in the Vite configuration file or in the Vite command line.
A preview image:
Principle
Appreciation
Contributing
- Fork it!
- Create your feature branch: git checkout -b my-new-feature
Debugging
In development environment
# packages/vite-plugin-fake-server
npm run build:watch
# packages/playground/react-sample
npm run dev
In production environment
# packages/vite-plugin-fake-server
npm run build:watch
# packages/playground/react-sample
npm run build
npm run preview
- Commit your changes: git commit -am "Add some feature"
- Push to the branch: git push origin my-new-feature
- Submit a pull request :D
License
MIT License © 2023-Present Condor Hero