Webpack最简朴的体式格局Mock API

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

装置

npm install webpack-api-mocker --save-dev

运用

定义API,假定我们讲API放到一个自力文件 mocker/index.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 项目中运用 api mocker,只需将设置选项,增加到你的 webpack-dev-server 选项中即可:

转变你的配置文件,通知dev服务器在那里查找文件:webpack.config.js。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const apiMocker = require('webpack-api-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/',
+       },
+       changeHost: true,
+     })
+   }
+ },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Development'
    })
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

模仿API代办变得简朴。

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

让我们增加一个脚原本轻松运转开辟服务器:

修正 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 path = require('path');
const express = require('express');
+ const apiMocker = require('webpack-api-mocker');

const app = express();

+ apiMocker(app, path.resolve('./mocker/index.js'))
app.listen(8080);
    原文作者:小弟调调
    原文地址: https://segmentfault.com/a/1190000013220134
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞