webpack-api-mocker 是一個爲 REST API 建立 mock 的 webpack-dev-server 中間件。 當您嘗試在沒有實際的 REST API 服務器的狀況下,測試您的應用程序時,這將會頗有幫助。css
npm install webpack-api-mocker --save-dev
定義API,假設咱們講API放到一個獨立文件 mocker/index.js
中, 下面咱們定義四個 API
,每一個 API
都放到 json
的 key
和 value
中,以下:html
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
比較特殊,由 methd
和 path
組合,中間一個空格間隔,如:GET /api/user
。value
能夠是 json
或者 函數
。webpack
要在你的 Webpack
項目中使用 api mocker
,只需將設置選項,添加到你的 webpack-dev-server 選項中便可:git
改變你的配置文件,告訴dev服務器在哪裏查找文件:webpack.config.js。github
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代理變得簡單。web
{ before(app){ + apiMocker(app, path.resolve('./mocker/index.js'), { + proxy: { + '/repos/*': 'https://api.github.com/', + }, + changeHost: true, + }) } }
讓咱們添加一個腳原本輕鬆運行開發服務器:express
修改 package.json
npm
{ "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是否能返回結果。json
npm run start
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);