Frontend Development 20 min read

Implementing Frontend Mock Functionality with Webpack, Configuration Decoupling, and Request Wrappers

This article explains how to build a flexible front‑end mock system by decoupling configuration files, extending webpack devServer proxy hooks, creating a unified request wrapper with Axios, and generating minimal mock.json files for both development and production builds.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Implementing Frontend Mock Functionality with Webpack, Configuration Decoupling, and Request Wrappers

The article starts by outlining the essential mock features a front‑end developer expects, such as configuration decoupling, multiple mock scenarios per API, header‑based mock selection, and the ability to inject mock data into production bundles.

Configuration decoupling is achieved by generating a conf.json file at build or dev time; the file contains project name, version, ports, API prefixes, debug flags, delay settings, and a mock map that links mock-key.method to a specific response (e.g., "login.logout": "success" ). The directory layout includes config/ , src/ , and a non‑tracked api-cache/ for cached real responses.

├── config
│   ├── conf.json            # git ignored
│   ├── config.js
│   └── config_default.js
├── src
│   ├── pages/login/login-io.js
│   └── pages/login/login-mock.json
└── api-cache                # git ignored
    ├── login.login.json
    └── login.logout.json

Webpack’s devServer.proxy is extended with custom onProxyReq and onProxyRes hooks (implemented in scripts/api-proxy-cache.js ). onProxyReq reads the request body, extracts mock-key and mock-method headers, and, if a matching mock entry exists, returns the mock response directly. onProxyRes caches successful real responses into api-cache for later mock generation.

module.exports = {
  onProxyReq: async (_, req, res) => { /* read body, check mock headers */ },
  onProxyRes: async (res, req) => { /* cache real response */ },
  onError(err, req, res) { /* fallback error handling */ }
};

The unified request wrapper ( src/io/index.jsx ) builds on Axios, providing default headers, automatic error handling, login redirection, mock injection (via headers mock-key and mock-method ), and optional delay for mock responses. It also supports a simple “rejectToData” mode that maps plain parameters to request bodies.

export const request = creatRequest({
  headers: {'Content-Type': 'application/json'},
  action: (data) => { /* handle unauthenticated case */ },
  delay: config.delay,
  showError: true,
  throwError: false
});

The createIo helper generates API functions from a descriptor object, automatically adding mock headers in development mode or injecting pre‑built mock data in production. It merges per‑environment configuration, resolves URL prefixes, and forwards the final options to the request wrapper.

export const createIo = (ioContent, name = '') => {
  const content = {};
  Object.keys(ioContent).forEach(key => {
    content[key] = async (options = {}) => { /* build request options */ };
  });
  return content;
};

A build script ( scripts/build-mock.js ) scans all *-mock.json files, merges them according to the conf.json.mock map, and writes a minimized mock.json used by the production bundle. It also watches configuration changes during development to regenerate the files on the fly.

In conclusion, the article demonstrates a complete workflow for front‑end mock implementation: from decoupled configuration, through proxy‑level request interception and caching, to a reusable request abstraction and automated mock file generation, enabling developers to work without a back‑end and to keep mock data consistent across environments.

frontendproxyConfigurationWebpackMockAxiosDevtools
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.