webpack5之前使用的是devServer.before
来配置mock服务, 到了webpack5则改为devServer.setupMiddlewares
参考文档: https://webpack.js.org/configuration/dev-server/#devserversetupmiddlewares
mock相关代码
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
}
apis/test.js
const { handleReq } = require('../utils')
module.exports = {
getUser: (devServer) => {
handleReq(devServer, {
url: '/users',
method: 'get',
json: 'userInfo.json',
})
},
}
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配置
代码语言:javascript复制devServer: {
setupMiddlewares: './mock/index.js'
}