Vite Plugin Fake Server
vite-plugin-fake-server provides a robust fake server solution for Vite development environments, intercepting both XHR and Fetch requests to simulate API responses. The current stable version is 2.2.3, and the project demonstrates an active release cadence with frequent bug fixes and feature enhancements, including recent compatibility updates for Vite 8. Key differentiators include its agnostic approach to data generation libraries (allowing use of Faker.js, Mock.js, etc.), support for both ESM and CommonJS modules, comprehensive TypeScript typings via `defineFakeRoute`, and compatibility with various file types (`.ts`, `.js`, `.mjs`, etc.). It also supports custom HTTP headers, status codes, and can even be configured for independent deployment, offering flexibility for mocking in both development and production scenarios.
Common errors
-
TypeError: defineFakeRoute is not a function
cause The `defineFakeRoute` utility was imported from the main package instead of the specific `/client` subpath.fixChange the import statement to `import { defineFakeRoute } from 'vite-plugin-fake-server/client'`. -
Module not found: Can't resolve 'vite-plugin-fake-server/client'
cause This error typically occurs if the subpath export for `/client` is not correctly resolved by your module bundler or if the package installation is corrupted.fixEnsure `vite-plugin-fake-server` is correctly installed. Try deleting `node_modules` and `package-lock.json` (or `yarn.lock`) and reinstalling dependencies. Verify your Vite configuration for any unusual alias settings. -
Fake server routes are not updating or new fake files are not detected in development.
cause This indicates an issue with the file watcher, which was a known problem in older versions, particularly with `chokidar@v4`.fixUpgrade `vite-plugin-fake-server` to version 2.2.0 or higher, which includes fixes for watcher-related issues. Also, verify that your Vite configuration's `include` option in the plugin matches your fake route file directory.
Warnings
- breaking Older versions of `vite-plugin-fake-server` might not be compatible with newer Vite versions. Specifically, ensure you are using v2.2.3 or higher for compatibility with Vite 8, and v2.1.3 or higher for Vite 6.
- gotcha When defining fake routes, the `defineFakeRoute` function must be imported from `vite-plugin-fake-server/client`. Forgetting the `/client` subpath will lead to import errors.
- gotcha Users on older versions (pre-v2.2.2) might encounter issues with request bodies being missing in Firefox when using XHR/Fetch, due to a bug in the underlying `xhook` library.
- gotcha File watcher issues, particularly with `chokidar@v4`, preventing new fake route files from being detected or changes from being reloaded, were present in versions prior to v2.2.0.
Install
-
npm install vite-plugin-fake-server -
yarn add vite-plugin-fake-server -
pnpm add vite-plugin-fake-server
Imports
- vitePluginFakeServer
const vitePluginFakeServer = require('vite-plugin-fake-server')import { vitePluginFakeServer } from 'vite-plugin-fake-server' - defineFakeRoute
import { defineFakeRoute } from 'vite-plugin-fake-server'import { defineFakeRoute } from 'vite-plugin-fake-server/client' - FakeRoute
import type { FakeRoute } from 'vite-plugin-fake-server/client'
Quickstart
import { defineConfig } from "vite";
import { vitePluginFakeServer } from "vite-plugin-fake-server";
import { faker } from "@faker-js/faker";
import Mock from "mockjs";
import { defineFakeRoute } from "vite-plugin-fake-server/client";
// vite.config.ts
export default defineConfig({
plugins: [
vitePluginFakeServer({
// Optional: specify base directory for fake routes
include: 'fake',
// Other options can go here, e.g., enable: true
}),
],
});
// fake/user.fake.ts (create this file in the 'fake' directory)
export default defineFakeRoute([
{
url: '/mock/get-user-info',
method: 'GET',
response: () => {
return Mock.mock({
id: '@guid',
username: '@first',
email: '@email',
avatar: '@image("200x200")',
role: 'admin',
});
},
},
{
url: '/fake/get-user-info-faker',
method: 'GET',
response: () => {
return {
id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate().toISOString().split('T')[0],
email: faker.internet.email(),
firstName: faker.person.firstName(),
lastName: faker.person.lastName(),
sex: faker.person.sexType(),
role: 'user',
};
},
},
]);
// Example client-side usage (e.g., in App.vue or index.ts)
async function fetchUserInfo() {
try {
const mockResponse = await fetch('/mock/get-user-info');
const mockData = await mockResponse.json();
console.log('Mock.js user info:', mockData);
const fakerResponse = await fetch('/fake/get-user-info-faker');
const fakerData = await fakerResponse.json();
console.log('Faker.js user info:', fakerData);
} catch (error) {
console.error('Failed to fetch user info:', error);
}
}
fetchUserInfo();