用webpack的中间件devServer来布置本地mock数据
2022-02-22 本文已影响0人
fred_33c7
参考官方文档:https://webpack.js.org/configuration/dev-server/
1.在config文件夹编写mock.config.js来编写mock中间件
const fs = require('fs');
const path = require('path');
function response(res, content, type = 'json') {
res.type(type);
res.write(content);
res.end();
}
function mock(res, file) {
fs.readFile(file, 'utf8', (error, content) => {
if (error) {
response(res, error.message, 'html');
}
response(res, content, 'json');
});
}
const mockMiddleware = (config) => (req, res, next) => {
const { projectDir, mockDir } = config;
if (['.html', '.css', '.js', '.png', '.jpg'].indexOf(path.extname(req.path)) > -1) {
return next();
}
const filePath = path.resolve(projectDir, `./${mockDir + req.path}.json`);
console.log('filePath', filePath);
return fs.stat(filePath, (error) => {
if (error) {
next();
} else {
mock(res, filePath);
}
});
};
module.exports = mockMiddleware;
2.在webpack.dev.config.js中添加devServer中间件
devServer: {
contentBase: path.join(__dirname, '.'),
historyApiFallback: false,
hot: false,
host: '0.0.0.0',
port: PORT,
before(app) {
const projectDir = path.resolve();
const mockDir = './mock';
app.use(mockMiddleware({ projectDir, mockDir }));
},
},
- 编写本地mock数据
例如:
mock->students->studentA.json
{
"age": 18,
"status": "success",
"grade": {
"English": 99,
"Math": 92
}
}
- 获取mock数据
axios.get('/students/studentA').then((res) => {
console.log('res', res.data);
}).catch((error) => {
console.log(error);
});