Webpack最简单的方式Mock API

8,089 阅读2分钟

mocker-api 是一个为 REST API 创建 mock 的 webpack-dev-server 中间件。 当您尝试在没有实际的 REST API 服务器的情况下,测试您的应用程序时,这将会很有帮助。

安装

npm install mocker-api --save-dev

使用

定义API,假设我们讲API放到一个独立文件 mocker.js 中, 下面我们定义四个 API,每个 API 都放到 jsonkeyvalue 中,如下:

const proxy = {
  'GET /api/user': {id: 1, username: 'kenny', sex: 6 },
  'GET /api/user/list': [
    {id: 1, username: 'kenny', sex: 6 },
    {id: 2, username: 'kenny', sex: 6 }
  ],
  'POST /api/login/account': (req, res) => {
    const { password, username } = req.body;
    if (password === '888888' && username === 'admin') {
      return res.send({
        status: 'ok',
        code: 0,
        token: "sdfsdfsdfdsf",
        data: {id: 1, username: 'kenny', sex: 6 }
      });
    } else {
      return res.send({status: 'error', code: 403 });
    }
  },
  'DELETE /api/user/:id': (req, res) => {
    console.log('---->', req.body)
    console.log('---->', req.params.id)
    res.send({ status: 'ok', message: '删除成功!' });
  }
}
module.exports = proxy;

上面的 key 比较特殊,由 methdpath 组合,中间一个空格间隔,如:GET /api/uservalue 可以是 json 或者 函数

命令行中使用

⚠ ️不依赖于webpack和webpack-dev-server。

# 全局安装依赖.
npm install mocker-api -g
# 运行服务
mocker ./mocker/index.js

或者您可以将 mocker-api 在当前项目安装,配置运行脚本命令。

{
  "name": "base-example",
  "scripts": {
+    "api": "mocker ./mocker"
  },
  "devDependencies": {
+    "mocker-api": "^1.6.4"
  },
  "license": "MIT"
}

在 Webpack 中使用

要在你的 Webpack 项目中使用 api mocker,只需将设置选项,添加到你的 webpack-dev-server 选项中即可:

改变你的配置文件,告诉dev服务器在哪里查找文件:webpack.config.js。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
+ const apiMocker = require('mocker-api');
+ const mocker = require('./mocker');

module.exports = {
  entry: {
    app: './src/index.js',
    print: './src/print.js'
  },
  devtool: 'inline-source-map',
+ devServer: {
+   ...
+   before(app){
+     apiMocker(app, path.resolve('./mocker/index.js'), {
+       proxy: {
+         '/repos/*': 'https://api.github.com/',
+         '/:owner/:repo/raw/:ref/*': 'http://127.0.0.1:2018'
+       },
+       changeHost: true,
+     })
+   }
+ },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Development'
    })
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

让我们添加一个脚本来轻松运行开发服务器:

修改 package.json

{
  "name": "development",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --progress --watch",
+   "start": "webpack-dev-server --open",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^0.1.16",
    "css-loader": "^0.28.4",
    "csv-loader": "^2.1.1",
    "file-loader": "^0.11.2",
    "html-webpack-plugin": "^2.29.0",
    "style-loader": "^0.18.2",
    "webpack": "^3.0.0",
    "xml-loader": "^1.2.1"
  }
}

运行下面命令,跑起来,通过工具测试一下你模拟的API是否能返回结果。

npm run start

Express 中使用

const express = require('express');
+ const path = require('path');
+ const apiMocker = require('mocker-api');

const app = express();

+ apiMocker(app, path.resolve('./mocker/index.js'))
app.listen(8080);