Registry / http-networking / webpack-mock-server

webpack-mock-server

JSON →
library1.0.23jsnpmunverified

Webpack Mock Server is an Express.js middleware designed to integrate seamlessly with `webpack-dev-server` for API request mocking during development. It boasts a built-in hot-replacement (HMR) mechanism and a TypeScript compiler, allowing developers to define mock responses using `.js`, `.ts`, and `.json` files. The current stable version is `1.0.23`, with an active maintenance cadence demonstrated by frequent point releases addressing compatibility and bug fixes. A key differentiator is its ability to display all configured mock endpoints in a user-friendly `index.html` interface, accessible directly from the console. Unlike traditional proxy setups, it functions as a middleware, avoiding complex proxy-path-patterns while maintaining the ability to use ordinary `fetch('/api/getUserInfo')` calls. It can also operate as a standalone Express middleware without Webpack. This approach simplifies development workflow by providing a robust and integrated mocking solution.

npm install webpack-mock-server
INSTALL
IMPORT
SIG · WEBPACK-MOCK-SERVE
W
webpack-mock-server
http-networkingjavascriptv1.0.23
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

webpackMockServer
✓ const webpackMockServer = require("webpack-mock-server");
This CommonJS `require` syntax is typically used in `webpack.config.js` for setting up the middleware.
webpackMockServer
✓ import webpackMockServer from "webpack-mock-server";
✗ const webpackMockServer = require('webpack-mock-server');
This ESM `import` syntax is the preferred method for `webpack.mock.ts` (or `.js` when using ESM) to access the main module.
webpackMockServer.add
✓ export default webpackMockServer.add((app, helper) => { /* ... */ });
✗ import { add } from 'webpack-mock-server';
The `add` method is exposed directly on the default `webpackMockServer` export and is used to register individual mock definitions. It is not a named export from the package root.

Initializes `webpack-mock-server` within `webpack-dev-server` to define and serve basic GET and POST API mock endpoints, demonstrating file-based responses and multiple mock entries.

/* 1. Create webpack.config.js 2. Create webpack.mock.ts 3. Create src/index.ts (can be empty) 4. Create tsconfig.json (minimal) if using TS 5. npm install --save-dev webpack webpack-cli webpack-dev-server webpack-mock-server typescript ts-loader express @types/express */ // webpack.config.js const webpackMockServer = require("webpack-mock-server"); const path = require("path"); module.exports = { mode: 'development', entry: './src/index.ts', // Dummy entry for webpack to run devServer: { port: 8080, setupMiddlewares: (middlewares, devServer) => { webpackMockServer.use(devServer.app, { port: (devServer.options.port || 8080) + 1, // Mock server runs on 8081 by default logLevel: 'info', // Optional: for detailed logging entry: path.resolve(__dirname, 'webpack.mock.ts'), // Explicitly define mock entry point }); return middlewares; }, }, // Minimal webpack config to make devServer run output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, resolve: { extensions: ['.ts', '.js'], }, module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, }; // webpack.mock.ts import webpackMockServer from "webpack-mock-server"; import nodePath from "path"; import { Express } from 'express'; // Import Express types for 'app' // Simulate content of a 'response.json' file for demonstration const dummyResponseJsonContent = { status: "success", data: "Mocked data from JSON file!", timestamp: new Date().toISOString() }; export default webpackMockServer.add((app: Express, helper) => { // GET endpoint example app.get("/api/users", (_req, res) => { res.json({ message: "List of users from mock server. Random ID: " + helper.getRandomInt() }); }); // POST endpoint example with body parsing app.post("/api/users", (req, res) => { const newUser = req.body; res.status(201).json({ message: "User created successfully", user: newUser, mockTimestamp: new Date().toISOString() }); }); // GET endpoint returning a simulated file content app.get("/api/config", (_req, res) => { // In a real scenario, this would load from disk: res.sendFile(nodePath.join(__dirname, "./response.json")); res.json(dummyResponseJsonContent); }); }); // Optional: Export another mock definition (multiple exports are supported) export const analyticsMock = webpackMockServer.add((app: Express, helper) => { app.get("/api/analytics", (_req, res) => { res.json({ views: helper.getRandomInt(100, 1000), clicks: helper.getRandomInt(10, 100) }); }); }); // Minimal tsconfig.json (if using TypeScript) /* { "compilerOptions": { "target": "es2016", "module": "commonjs", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true } } */ // Dummy src/index.ts (can be empty) // console.log("Webpack app running");
Debug
Known issues
gotchaOlder versions of `webpack-mock-server` (prior to `v1.0.22`) may encounter compatibility issues with newer `webpack-dev-server` releases, leading to the mock server failing to initialize or operate correctly.
fix
Upgrade to `webpack-mock-server@^1.0.22` or a later version to ensure compatibility with modern `webpack-dev-server` setups by running `npm install webpack-mock-server@latest`.
affects: <1.0.22
gotcha`webpack-mock-server` explicitly requires `typescript`, `express`, and `@types/express` to be installed as peer dependencies. Failure to install these, especially `typescript` even when using JavaScript (`.js`) mock files, will result in errors during compilation or startup.
fix
Ensure all required peer dependencies are installed in your project: `npm install --save-dev webpack-mock-server typescript express @types/express`.
affects: >=1.0.0
gotchaVersions prior to `v1.0.23` had issues correctly parsing `formData` with nested dot-notation properties, as well as `Date` objects and primitive values within `req.body` from JSON payloads. This could lead to unexpected or unparsed data in your mock handlers.
fix
Update to `webpack-mock-server@^1.0.23` to resolve known issues with `req.body` parsing for `formData` and `Date` types by running `npm install webpack-mock-server@latest`.
affects: <1.0.23
gotchaBy default, `webpack-mock-server` often runs on a port one greater than your `webpack-dev-server`'s configured port (e.g., `8081` if `webpack-dev-server` is on `8080`). This is an intentional design choice to avoid port conflicts but can be unexpected if you assume it will run on the exact same port or don't account for it.
fix
Be aware of the default port offset. Configure the `port` option explicitly in `webpackMockServer.use` if you need a specific port or wish to override this behavior, e.g., `{ port: 8081 }`.
affects: >=1.0.0
Errors
Common errors & fixes
Cannot find module 'typescript'
The `typescript` peer dependency is missing from your project's `node_modules`.
fix
Install `typescript` as a development dependency: `npm install --save-dev typescript` or `yarn add -D typescript`.
TypeError: app.get is not a function (or similar Express method error like req.body, res.json)
The `express` or `@types/express` peer dependencies are missing, leading to `app` not being a valid Express application instance or its types being undefined.
fix
Install `express` and its type definitions: `npm install --save-dev express @types/express` or `yarn add -D express @types/express`.
webpack-mock-server: Not running on recent webpack-dev-server versions (or silent failure of mock endpoints)
Your `webpack-mock-server` version is outdated and incompatible with the `webpack-dev-server` version you are using.
fix
Update `webpack-mock-server` to the latest compatible version: `npm update webpack-mock-server` or `npm install webpack-mock-server@latest`.
req.body is empty, undefined, or contains unparsed data when expecting JSON/formData in mock handler
Prior to `v1.0.23`, there were known issues with `webpack-mock-server`'s internal body parsing for `formData`, `Date` objects, and dot-notation properties.
fix
Ensure `webpack-mock-server` is updated to `v1.0.23` or later to leverage parsing fixes. If the issue persists, explicitly adding `app.use(express.json());` or `app.use(express.urlencoded({ extended: true }));` at the start of your mock definition file might help.
Upgrade
Version history
1.0.23latest on npm
Audit
Dependencies
expressrequiredRequired as `webpack-mock-server` is an Express.js middleware. It needs Express to define routes and handle requests.
typescriptrequiredExplicitly required as a peer dependency for compilation, even when using JavaScript (`.js`) mock files. Critical for the built-in TypeScript compiler.
@types/expressrequiredEssential for TypeScript projects to provide type definitions for Express.js, enabling type-safe mock endpoint definitions.
@types/multeroptionalListed as a peer dependency, potentially needed for type definitions related to `formData` parsing if Multer is used implicitly or explicitly.
Agent activity
21 hits · last 30 days
node
18
OpenAI (training)
1
Resources
webpack-mock-server — npm install webpack-mock-server · libregistry