Webpack5结合mockjs

webpack5之前使用的是devServer.before来配置mock服务, 到了webpack5则改为devServer.setupMiddlewares

参考文档: https://webpack.js.org/configuration/dev-server/#devserversetupmiddlewares

mock相关代码

  1. mock/index.js
const Test= require('./apis/test')

const obj = {
  ...Test,
}

module.exports = function (middlewares, devServer) {
  Object.keys(obj).forEach((v) => {
    obj[v](devServer)
  })

  return middlewares
}
  1. apis/test.js
const { handleReq } = require('../utils')

module.exports = {
  getUser: (devServer) => {
    handleReq(devServer, {
      url: '/users',
      method: 'get',
      json: 'userInfo.json',
    })
  },
}
  1. mock/utils.js
const Mock = require('better-mock')
module.exports = {
  handleReq: (devServer, config) => {
    const { method, url, json } = config
    devServer.app[method]('/mock/api' + url, function (_, res) {
      res.json(Mock.mock(json))
    })
  },
}

webpack配置

devServer: {
    setupMiddlewares: './mock/index.js'
}

你可能感兴趣的:(Webpack5结合mockjs)