2019-04-07

在Vue项目中使用webpack-api-mocker进行mock

Webpack最简单的方式Mock API

安装 webpack-api-mocker
npm i webpack-api-mocker --save-dev

新建 /data.json

新建 /mocker/index.js

const appData = require('../data.json')
const seller = appData.seller
const goods =appData.goods
const ratings = appData.ratings

const proxy = {
  'GET /api/seller': {errno:0,seller:seller},
  'GET /api/goods': {goods:0,data:goods},
  'POST /api/ratings': {goods:0,ratings:ratings},
}
module.exports = proxy;

在 /vue.config.js 中配置

const path = require('path')
const apiMocker = require('webpack-api-mocker')

module.exports = {
  devServer: {
    before(app) {
      apiMocker(app, path.resolve('./mocker/index.js'), {
        proxy: {
          '/repos/*': 'https://api.github.com/',
        },
        changeHost: true,
      })
    }
  }
}

这样启动项目后,就可以直接请求mock数据了。