Webpack5结合mockjs

2022-09-28 15:28:44 浏览数 (1)

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

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

mock相关代码

  1. mock/index.js
代码语言:javascript复制
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
代码语言:javascript复制
const { handleReq } = require('../utils')

module.exports = {
  getUser: (devServer) => {
    handleReq(devServer, {
      url: '/users',
      method: 'get',
      json: 'userInfo.json',
    })
  },
}
  1. mock/utils.js
代码语言:javascript复制
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配置

代码语言:javascript复制
devServer: {
    setupMiddlewares: './mock/index.js'
}

0 人点赞