Installations
npm install webpack-mock-server
Developer Guide
Typescript
Yes
Module System
CommonJS
Min. Node Version
>=8.9.0
Node Version
20.15.1
NPM Version
10.7.0
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (73.43%)
HTML (14.61%)
JavaScript (11.97%)
Developer
Yegorich555
Download Statistics
Total Downloads
116,844
Last Day
64
Last Week
425
Last Month
2,770
Last Year
35,081
GitHub Statistics
15 Stars
232 Commits
1 Forks
3 Watching
4 Branches
2 Contributors
Package Meta Information
Latest Version
1.0.22
Package Id
webpack-mock-server@1.0.22
Unpacked Size
93.64 kB
Size
25.25 kB
File Count
31
NPM Version
10.7.0
Node Version
20.15.1
Publised On
16 Oct 2024
Total Downloads
Cumulative downloads
Total Downloads
116,844
Last day
-66.7%
64
Compared to previous day
Last week
-50.5%
425
Compared to previous week
Last month
12.2%
2,770
Compared to previous month
Last year
-15.2%
35,081
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Peer Dependencies
3
Dev Dependencies
21
Webpack Mock Server
ExpressJs Middleware for webpack-dev-server with built-in hot-replacement (HMR) and typescript compiler. Uses for mocking api responses
Features
- Typescript support (>=v2.7): supports .js, .ts, .json files
- ES6 export/import support
- Hot replacement support
- Does not require proxy-path-pattern (because this is middleware that pipes routes to splitted server without proxy-path-pattern)
- Can be used without webpack (because this is expressjs middleware)
- Shows every configured response in user-friendly index.html (just click on mock-server-url in console after as mockServer is started)
Installing
Using npm (installing Typescript is required even if you don't use ts files):
1npm i --save-dev webpack-mock-server typescript @types/express
Examples
Usage with defaults
1// webpack.config.js - ver 5+ 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( 39 "JS delete-object can be here. Random int:" + helper.getRandomInt() 40 ); 41 }); 42 app.put("/testPut", (_req, res) => { 43 res.json("JS put-object can be here"); 44 }); 45});
Usage with multiple/custom entries (instead of default webpack.mock.ts)
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})
Usage with multiple entries by pattern (wildcard)
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
Usage without webpack
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...
Usage with the whole default config
for webpack v5+
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...
for webpack v4
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...
Options
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: |
MockServerHelper. Methods
- .getRandomInt(min = 0, max = 2147483648) ⇒
Number - returns random integer between min and max
- .getUniqueIdInt() ⇒
Number - returns unique integer
Troubleshooting
- It's important to install Typescript even if use only JS-files (webpack-mock-server uses ts-compiler for gathering ts,js,json files)
- Don't use NodeJs require operator as dynamic to relative path. Use dirname in this case or absolute path (dirname is changed during the compilation)
- NodeJs caches every required module (file), so you maybe interested in clearing cache for require(.json)*.
Use
delete require.cache[require.resolve({yourPathName})]
before you callrequire({yourPathName})
; - Mockserver can't compile the TS-code.
Possible reason: you have some extra import OR missed some global files (like
global.d.ts
). Solution: all mock-files must be without dependencies (imports) of components defined in the main-project files- If you have custom
tsconfig.mock.json
file check if all required\*d.ts
files are included.. include: ["**/global.d.ts", ..] ..
- To check what's wrong check compilation trace
npx tsc --project tsconfig.mock.json --generateTrace traceDir
OR enable logging via optionverbose:true
- If you have custom
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( 22 nodePath.join(__dirname, "./response.json") 23 ); 24 // removing NodeJS cache for getting the latest file 25 delete require.cache[resolvedPath]; 26 res.json(require(resolvedPath)); 27});
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
3 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w
Reason
Found 0/14 approved changesets -- score normalized to 0
Reason
1 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 16 are checked with a SAST tool
Score
2.7
/10
Last Scanned on 2025-01-27
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 MoreOther packages similar to 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