vite-mock-api
is a Vite plugin that allows you to easily create and manage mock API endpoints for development. By defining simple mock handlers, you can simulate API responses without needing a separate backend, improving development speed and efficiency.
- Easy Mock API Setup: Just define your mock API handlers in a dedicated folder.
- Automatic Bundling: Uses esbuild to bundle mock handlers from TypeScript to CommonJS.
- Middleware Integration: Registers mock endpoints as middleware in the Vite development server.
- Development-Only Activation: The plugin runs only in development mode and does not affect production builds.
- Enhanced Request Handling: Parses query parameters and request bodies automatically.
-
Supports Custom Middleware: Allows adding third-party middleware (e.g.,
body-parser
). -
File Watching: Automatically reloads mock handlers when changes are detected. (watching
{mockFilesDir}/index.ts
, defaultmockFilesDir
="mock-api"
)
To install the plugin, run:
npm install -D vite-mock-api
or
yarn add -D vite-mock-api
or
pnpm add -D vite-mock-api
To use the plugin, import it and add it to your Vite configuration file (vite.config.ts
).
import { defineConfig } from "vite";
import mockApiPlugin from "vite-mock-api";
export default defineConfig({
plugins: [mockApiPlugin()],
// default mockFilesDir = "mock-api"
});
export default defineConfig({
plugins: [
mockApiPlugin({
mockFilesDir: "my-mock-api", // Optional: Change the mock API directory
middlewares: [], // Optional: Add custom middleware functions
}),
],
});
-
Create a
/{mockFilesDir}
Directory: In the root of your project, create a directory called{mockFilesDir}
.(default
mockFilesDir
="mock-api"
) -
Define Your API Handlers: Inside the
{mockFilesDir}
folder, create anindex.ts
file and export mock handlers.
// my-mock-api/index.ts
import {
MockHandler,
MockApiHandlerRequest,
MockApiHandlerResponse,
} from "vite-mock-api";
const helloHandler: MockHandler = {
path: "/api/hello",
handler: (req: MockApiHandlerRequest, res: MockApiHandlerResponse) => {
console.log(req.headers, req.query, req.params); // check your terminal console.
res.json({ message: "Hello, world!" }); // check your web console.
},
};
export default [helloHandler];
A request to:
GET http://localhost:5173/api/hello?name=John
will result in the following response:
{
"message": "Hello, world!"
}
- The plugin scans the
/{mockFilsDir}/index.ts
file when the Vite development server starts. - It bundles the mock handlers into a CommonJS module using esbuild.
- The bundled mock handlers are dynamically imported and registered as middleware in the Vite dev server.
- Requests matching the specified paths are intercepted and handled by the mock handlers.
- The plugin watches for changes in the mock API files and reloads the handlers automatically.
-
Query Parameters: Automatically parsed and available in
req.query
andreq.params
. -
Request Body: Automatically parsed and accessible via
req.body
. -
Custom JSON Response: The response object has a
json(data)
method for sending JSON responses. -
Custom Middleware: Allows third-party middleware (e.g.,
body-parser
) to be added before mock API handlers.
If you want request with body(POST, PATCH, PUT method)
request, you can add middleware functions to process requests before they reach mock handlers. See example code below.
import bodyParser from "body-parser";
import mockApiPlugin from "vite-mock-api";
export default defineConfig({
plugins: [
mockApiPlugin({
middlewares: [bodyParser.json()],
}),
],
});
-
Missing Mock Handlers: Ensure your
/{mockFilesDir}
directory andindex.ts
file exist. -
Development Mode: The plugin only runs in development mode (
vite
ornpm run dev
). - Bundling Issues: If esbuild fails, check your console logs for error messages.
-
Correct Export Format: Your
index.ts
file should export an array of handlers as the default export. -
File Watching Not Working: Ensure the file path is correctly set in
mockFilesDir
.
This plugin is licensed under the MIT License.
Contributions are welcome! If you have suggestions, find issues, or want to add features, feel free to open an issue or submit a pull request.
- Maintainer: Insoo Park(Humanwater)
- Email: lunatics384@gmail.com