Gathering detailed insights and metrics for webpack-mock-server
Gathering detailed insights and metrics for webpack-mock-server
Gathering detailed insights and metrics for webpack-mock-server
Gathering detailed insights and metrics for webpack-mock-server
webpack-dev-mock
Webpack devserver middleware mock server
express-proxy-mock
This is an express middleware that can be used with webpack and vite. Its main function is to visualize the configuration, manage proxies, and mock data.
mocker-api
This is dev support mock RESTful API.
webpack-mock-server-plugin
webpack-mock-server-plugin
npm install webpack-mock-server
Typescript
Module System
Min. Node Version
Node Version
NPM Version
69.1
Supply Chain
96.6
Quality
74.5
Maintenance
50
Vulnerability
99.6
License
TypeScript (73.45%)
HTML (14.35%)
JavaScript (12.2%)
Total Downloads
127,385
Last Day
29
Last Week
824
Last Month
2,633
Last Year
30,219
MIT License
16 Stars
236 Commits
1 Forks
2 Watchers
6 Branches
2 Contributors
Updated on Apr 29, 2025
Latest Version
1.0.23
Package Id
webpack-mock-server@1.0.23
Unpacked Size
95.76 kB
Size
25.83 kB
File Count
31
NPM Version
10.8.2
Node Version
20.18.1
Published on
Mar 11, 2025
Cumulative downloads
Total Downloads
Last Day
480%
29
Compared to previous day
Last Week
45.6%
824
Compared to previous week
Last Month
12.4%
2,633
Compared to previous month
Last Year
-31.5%
30,219
Compared to previous year
2
3
21
ExpressJs Middleware for webpack-dev-server with built-in hot-replacement (HMR) and Typescript compiler. Uses for mocking api responses
fetch('/api/getUserInfo')
instead of fetch('http://localhost:8081/api/getUserInfo')
. Despite on mock-server is hosted on another port, it adds proxy to webpackUsing npm (installing Typescript is required even if you don't use ts files):
1npm i --save-dev webpack-mock-server typescript @types/express
You can find example of real usage in repo web-react (see /components/account folder)
1// webpack.config.js - webpack v5+ 2const webpackMockServer = require("webpack-mock-server"); 3 4module.exports = { 5 devServer: { 6 setupMiddlewares: (middlewares, devServer) => { 7 webpackMockServer.use(devServer.app, { 8 port: (devServer.options.port || 8080) + 1, 9 }); 10 return middlewares; 11 }, 12 }, 13}; 14 15// webpack.mock.ts - feel free to mock responses yourself 16import webpackMockServer from "webpack-mock-server"; 17import nodePath from "path"; 18 19// app is express application 20export default webpackMockServer.add((app, helper) => { 21 // you can find more about express here: https://expressjs.com/ 22 app.get("/testGet", (_req, res) => { 23 res.json("JS get-object can be here. Random int:" + helper.getRandomInt()); 24 }); 25 app.post("/testPost", (_req, res) => { 26 res.json("JS post-object can be here"); 27 }); 28 29 // you can return any file easy. Example for json response from file: 30 app.get("/testResponseFromJsonFile", (_req, res) => { 31 res.sendFile(nodePath.join(__dirname, "./response.json")); 32 }); 33}); 34 35// multiple exports are supported 36export const result = webpackMockServer.add((app, helper) => { 37 app.delete("/testDelete", (_req, res) => { 38 res.json("JS delete-object can be here. Random int:" + helper.getRandomInt()); 39 }); 40 app.put("/testPut", (_req, res) => { 41 res.json("JS put-object can be here"); 42 }); 43});
1// webpack.config.js 2const webpackMockServer = require("webpack-mock-server"); 3 4module.exports = { 5 devServer: { 6 setupMiddlewares: (middlewares, devServer) => { 7 webpackMockServer.use(devServer.app, { // MockServerOptions here 8 entry: [ // exact fileNames are expected (no wildcard or folder - use custom tsConfig instead) 9 "api/users.mock.ts", 10 "api/goods.mock.js" 11 ], 12 before: (req, res, next) => { // you can use this for custom-logging instead of logResponses: true, logRequests: true 13 console.log(`Got request: ${req.method} ${req.url}`); 14 res.once("finish", () => { 15 console.log(`Sent response: ${req.method} ${req.url}`); 16 }) 17 next(); 18 } 19 }); 20 return middlewares; 21 } 22 } 23} 24 25// api/users.mock.ts 26... // take the example for ts-file above 27 28// api/goods.mock.js 29export default webpackMockServer.add((app, helper) => { 30 app.get("/testGetGoods", (_req, res) => { 31 res.json([{ 32 id: helper.getRandomInt(1, 999), 33 name: "pen" 34 }]); 35 }); 36})
1// webpack.config.js 2const webpackMockServer = require("webpack-mock-server"); 3 4// for webpack v5 5module.exports = { 6 devServer: { 7 setupMiddlewares: (middlewares, devServer) => { 8 webpackMockServer.use(devServer.app, { 9 /* set an empty-array or null to [entry], so entry will be defined 10 from 'files' and 'includes' sections in [tsConfigFileName] */ 11 entry: [], 12 tsConfigFileName: "mock/tsconfig.json" // use a different tsconfig-file that is contained entries 13 }); 14 return middlewares; 15 } 16 } 17} 18 19// for webpack v4 20module.exports = { 21 devServer: { 22 before: app => 23 webpackMockServer.use(app, { 24 /* set an empty-array or null to [entry], so entry will be defined 25 from 'files' and 'includes' sections in [tsConfigFileName] 26 */ 27 entry: [], 28 tsConfigFileName: "mock/tsconfig.json" // use a different tsconfig-file that is contained entries 29 }) 30 } 31} 32 33 34// ./mock/tsconfig.json 35{ 36 /* 37 * this is ordinary tsconfig file that overrides every option from [extends] - main tsconfig-file 38 */ 39 "extends": "../tsconfig.json", // you can point the main tsconfig file or remove that property if it's not required 40 "include": [ // wildcard-pattern is supported 41 "../mock/*", 42 "*.mock.ts", 43 "**/global.d.ts", 44 ], 45 "files": [], // beside 'include' option you can point exact files here 46 "exclude": ["*test.mock.ts"] // note: exclude option can override 'include' and 'files' options 47} 48
As Express middleware: http://expressjs.com/en/guide/using-middleware.html
1// webpack.config.js 2const webpackMockServer = require("webpack-mock-server"); 3 4const express = require('express'); 5const app = express(); 6 7webpackMockServer.use(app, {/*mockServerOptions*/}) 8... 9app.listen(1782); 10 11// webpack.mock.ts - example you can find above 12...
Details about webpack-dev-server v5 vs v4 see here
1// webpack.config.js 2... 3const webpackMockServer = require("webpack-mock-server"); 4 5module.exports = { 6 devServer: { 7 setupMiddlewares: (middlewares, devServer) => { // it's different for webpack v4 8 webpackMockServer.use(devServer.app, { 9 port: (devServer.options.port || 8080) + 1, // app searches for free port (starts searching from pointed) 10 verbose: false, // send info via console.log 11 logRequests: false, 12 logResponses: false, 13 before: undefined, //can be used for logging 14 entry: ["webpack.mock.ts"], 15 tsConfigFileName: "tsconfig.json", 16 compilerOptions: { // typescript.CompilerOptions that override tsconfig.json:[compilerOptions] 17 strictNullChecks: false, 18 noImplicitAny: false, 19 noUnusedLocals: false, 20 noUnusedParameters: false, 21 skipLibCheck: true, 22 resolveJsonModule: true, 23 }, 24 strictCompilerOptions: { // these options impossible to override 25 outDir: "" // used the following: {os.tmpdir()}/webpack-mock-server/{new Date().getTime()} 26 rootDir: process.cwd(), 27 noEmit: false, 28 noEmitHelpers: false, 29 esModuleInterop: true, 30 module: ts.ModuleKind.CommonJS, 31 declaration: false, 32 moduleResolution: ModuleResolutionKind.Node10, 33 target: defineTarget() // it defines target-ES based on NODE version 34 } 35 }); 36 return middlewares; 37 } 38 } 39} 40 41// webpack.mock.ts - example you can find above 42...
1// webpack.config.js 2... 3const webpackMockServer = require("webpack-mock-server"); 4 5module.exports = { 6 devServer: { 7 before: app => // it's different for webpack v5 8 webpackMockServer.use(app, { 9 port: 8081, // app searches for free port (starts searching from pointed) 10 verbose: false, // send info via console.log 11 logRequests: false, 12 logResponses: false, 13 before: undefined, //can be used for logging 14 entry: ["webpack.mock.ts"], 15 tsConfigFileName: "tsconfig.json", 16 compilerOptions: { // typescript.CompilerOptions that override tsconfig.json:[compilerOptions] 17 strictNullChecks: false, 18 noImplicitAny: false, 19 noUnusedLocals: false, 20 noUnusedParameters: false, 21 skipLibCheck: true, 22 resolveJsonModule: true 23 }, 24 strictCompilerOptions: { // these options impossible to override 25 outDir: "" // used the following: {os.tmpdir()}/webpack-mock-server/{new Date().getTime()} 26 rootDir: process.cwd(), 27 noEmit: false, 28 noEmitHelpers: false, 29 esModuleInterop: true, 30 module: ts.ModuleKind.CommonJS, 31 declaration: false, 32 moduleResolution: ModuleResolutionKind.Node10, 33 target: defineTarget() // it defines target-ES based on NODE version 34 } 35 }) 36 } 37} 38 39// webpack.mock.ts - example you can find above 40...
Note: Every path-file-name in options has to be pointed relative to the currentWorkingDirectory (process.cwd() in NodeJs) or point an absolute path
Param | Type | Default | Description |
---|---|---|---|
entry | String, String[], null | ["webpack.mock.ts"] | Entry points for typescript-compiler (exact fileNames are expected). Set an empty array or null for using files, include and exlcude sections from tsConfigFileName. Otherwise these sections are ignored! |
port | Number | 8079 | App searches for free port (starts searching from pointed) |
verbose | Boolean | false | Show debug info in NodeJs via console.log |
logResponses | Boolean | false | Show responses-info in NodeJs via console.log |
logRequests | Boolean | false | Show request-info in NodeJs via console.log |
before | (req, res, next) => void | undefined | Execute custom middleware prior to all other middleware internally within the server Can be used for custom-logging. Example here |
compilerOptions | typescript.CompilerOptions | ... | See the latest example above |
strictCompilerOptions | typescript.CompilerOptions | ... | readOnly. See the latest example above. These options impossible to override |
tsConfigFileName | String | "tsconfig.json" | Pointer to typescript config file. Example here: |
Number - returns random integer between min and max
Number - returns unique integer
delete require.cache[require.resolve({yourPathName})]
before you call require({yourPathName})
;global.d.ts
).
Solution: all mock-files must be without dependencies (imports) of components defined in the main-project files
tsconfig.mock.json
file check if all required \*d.ts
files are included .. include: ["**/global.d.ts", ..] ..
npx tsc --project tsconfig.mock.json --generateTrace traceDir
OR enable logging via webpack-mock-server option verbose:true
1// Wrong 2app.get("/testResponseFromJsonFile", (_req, res) => { 3 res.sendFile(require.resolve("./response.json")); 4}); 5 6app.get("/testResponseFromJsonFile2", (_req, res) => { 7 res.json(require("./response.json")); 8}); 9 10// Correct 11import nodePath from "path"; 12 13app.get("/testResponseFromJsonFile", (_req, res) => { 14 res.sendFile(nodePath.join(__dirname, "./response.json")); 15}); 16 17app.get("/testResponseFromJsonFile2", (_req, res) => { 18 /* From NodeJs v8.9.0 you can use options: path 19 * const resolvedPath = require.resolve("./response.json", { paths: [__dirname] }); 20 */ 21 const resolvedPath = require.resolve(nodePath.join(__dirname, "./response.json")); 22 // removing NodeJS cache for getting the latest file 23 delete require.cache[resolvedPath]; 24 res.json(require(resolvedPath)); 25});
1/* Your ordinary http responses from UI */ 2 3// Wrong 4function apiGetUserInfo() { 5 return fetch("http://localhost:8081/api/getUserInfo"); // it works if webpack-mock-server hosted under 8081 port, but it's not correct usage 6} 7 8// Correct 9function apiGetUserInfo() { 10 return fetch("/api/getUserInfo"); // so if you run webpack-devServer with webpack-mock-server data returns webpack-mock-server if route exists; but if build your project then your API will be here 11}
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
2 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 1
Reason
9 existing vulnerabilities detected
Details
Reason
Found 0/13 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More