webpack-serve使用

webpack-serve 是一个轻量级的 webpack dev server,目前该项目已经停止维护,新项目建议使用 webpack-dev-server 代替。

webpack-serve 通过 http-proxy-middleware 插件,将请求灵活的转发到多个后端服务器。同时,由于所有请求都是通过 webpack-serve 转发的,可以避免跨域的问题

webpack-serve

命令行

webpack-serve ./webpack.config.js

or

webpack-serve --config ./webpack.config.js

API

const serve = require('webpack-serve');
const argv = {};
const config = require('./webpack.config.js');

serve(argv, { config }).then((result) => {
// ...
});

详细文档请参考:webpack serve repo

实例:

import serve from 'webpack-serve';
import config from './webpack.config.dev';
import { appPublic } from './paths';
import historyFalllback from './webpack-serve.addons/history-fallback.config';

serve({
    config,    // webpack 配置
    port: 8000,   // serve 服务端口
    content: [appPublic],  // 应用路径
    add: historyFalllback,  // 插件
});

插件:

'use strict';
import history from 'connect-history-api-fallback';
import convert from 'koa-connect';
import proxy from 'http-proxy-middleware';

export default (app: any, middleware: any, options: any) => {
    const historyOptions = {
    };

    // 将所有 http://localhost:8000/path/* 的请求
    // 路由到 http://x.x.x.x:8081/path/*
    // 注意端口的变化。
    app.use(convert(proxy('/path', { target: 'http://x.x.x.x:8081' })));

    // 其他的请求被路由到 index.html
    // 这对于单页应用特别有用
    app.use(convert(history(historyOptions)));
};

http-proxy-middleware

  • Proxy's docs

API

proxy([context,] config)

var proxy = require('http-proxy-middleware')

var apiProxy = proxy('/api', { target: 'http://www.example.org' })
//                   \____/   \_____________________________/
//                     |                    |
//                   context             options
  • context: 确定那些请求需要转发
  • options.target: 目标主机

Context 匹配

  • path matching

    匹配所有请求

      proxy({...})
    

    匹配所有请求

      proxy('/', {...})
    

    匹配以 /api 开头的请求

      proxy('/api', {...})
    
  • 匹配多个路径

      proxy(['/api', '/ajax', '/someotherpath'], {...})
    
  • 通配符

    匹配所有请求

      proxy('**', {...})
    

    匹配所有以html结尾的请求

      proxy('**/*.html', {...})
    

    匹配 / 下所有 html 结尾的请求,不包含子目录

      proxy('/*.html', {...})
    

    匹配 /api/ 下及其自目录下,以 html 结尾的请求

      proxy('/api/**/*.html', {...})
    

    匹配多个路径

      proxy(['/api/**', '/ajax/**'], {...})
    

    排除所有文件名为 bad.json 的请求

      proxy(['/api/**', '!**/bad.json'], {...})
    

    多路径匹配中, 字符串匹配和通配符匹配不能混用

  • 自定义匹配

      /**
      * @return {Boolean}
      */
      var filter = function(pathname, req) {
          return pathname.match('^/api') && req.method === 'GET'
      }
    
      var apiProxy = proxy(filter, { target: 'http://www.example.org' })
    

Fallback

  • Fallback's docs

你可能感兴趣的:(webpack-serve使用)