vite-mock-api
v1.0.2
Published
Mocking api server in vite.
Downloads
3
Maintainers
Readme
:gear: Vite Mock API Plugin
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.
Features
- 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")
Installation
To install the plugin, run:
npm install -D vite-mock-apior
yarn add -D vite-mock-apior
pnpm add -D vite-mock-apiUsage
To use the plugin, import it and add it to your Vite configuration file (vite.config.ts).
Example Configuration
Basic usage.
import { defineConfig } from "vite";
import mockApiPlugin from "vite-mock-api";
export default defineConfig({
plugins: [mockApiPlugin()],
// default mockFilesDir = "mock-api"
});Add plugin option.
export default defineConfig({
plugins: [
mockApiPlugin({
mockFilesDir: "my-mock-api", // Optional: Change the mock API directory
middlewares: [], // Optional: Add custom middleware functions
}),
],
});Setting Up Your Mock API Handlers
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.tsfile and export mock handlers.
Example Handler
// 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];Test above Request handler
A request to:
GET http://localhost:5173/api/hello?name=Johnwill result in the following response:
{
"message": "Hello, world!"
}How It Works
- The plugin scans the
/{mockFilsDir}/index.tsfile 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.
Request & Response Enhancements
- Query Parameters: Automatically parsed and available in
req.queryandreq.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.
Custom Middleware Support
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.
Example Using body-parser
import bodyParser from "body-parser";
import mockApiPlugin from "vite-mock-api";
export default defineConfig({
plugins: [
mockApiPlugin({
middlewares: [bodyParser.json()],
}),
],
});Troubleshooting
- Missing Mock Handlers: Ensure your
/{mockFilesDir}directory andindex.tsfile exist. - Development Mode: The plugin only runs in development mode (
viteornpm run dev). - Bundling Issues: If esbuild fails, check your console logs for error messages.
- Correct Export Format: Your
index.tsfile should export an array of handlers as the default export. - File Watching Not Working: Ensure the file path is correctly set in
mockFilesDir.
License
This plugin is licensed under the MIT License.
Contributing
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.
Author
- Maintainer: Insoo Park(Humanwater)
- Email: [email protected]
