background

You’ve probably all experienced frequent switching between mock data and request test environment interfaces, which required you to constantly change the Proxy for WebPack Dev Server and then restart the project. For large projects, restart costs are high. So is there any way to switch request targets without restarting? Can you control it by adding and removing parameters to the URL?

flex-mocker

Based on the above problems, I developed a Mock tool with WebPack Dev Server: flex-mocker

The characteristics of

You can switch between requesting mock data and requesting proxy interfaces at any time without restarting the project

  • Local mock data is requested by default

  • You can request the Webpack Proxy interface by adding mode=online search to the address bar

  • Mock files support hot updates and take effect immediately after modification

  • You can do simple logic on requests

Method of use

npm install flex-mocker --save-dev
Copy the code

After installation, create a new folder under your project to store your mock data

For example, if a request address is API /queryCities, create [Mock Folder]/ API /queryCities.json under the Mock folder

Querycities. json file contents:

{
  "code": "0"."msg": "success"."result": [{"city": "beijing"."code": 1 },
    { "city": "shanghai"."upcName": 2}]."success": true
}
Copy the code

Create a js file if you need to do some logic with the input parameter:

const dict1 = [{ type: 1.value: "1" }];

const dict2 = [{ label: "name".value: "1" }];

module.exports = req= > {
  // Get the input parameter
  const { dataType } = req.body;
  return {
    code: "0".msg: "success".dictionaryList: dataType === 1 ? dict1 : dict2,
    success: true
  };
};
Copy the code

Configure devServer for Webpack to take effect:

// Webpack configuration file
const mocker = require('flex-mocker')

devServer: {
  ...
  before: app= > {
    mocker({
      mockDir: resolve('./mock'),
      requestPrefixes: ['/api']
    })(app)
  },
  proxy: {... }}Copy the code

parameter

MockDir: The absolute path to the mock folder

RequestPrefixes: Request URL prefix to mock

Delay: indicates the response delay. The default value is 0

Write in the back

If you have a better idea, you are welcome to submit pr, click star if you think it will help šŸ˜, Portal: Flex-Mocker