browser-sync 和 http-proxy-middle

2019-01-31  本文已影响0人  温柔以待丶
const browserSync = require('browser-sync').create();
const proxy = require('http-proxy-middleware');

// 获取本地ip
function getIP() {
    const ifaces = require('os').networkInterfaces();
    let ip = '127.0.0.1';
    for (let dev in ifaces) {
        if (ifaces.hasOwnProperty(dev)) {
            ifaces[dev].forEach(details => {
                if (ip === '127.0.0.1' && details.family === 'IPv4') {
                    ip = details.address;
                }
            });
        }
    }
    return ip;
}

/* 代理中间件
 * 具体只用文档参考 https://www.jianshu.com/p/a248b146c55a
*/
let proxyArr =[
    // 代理转发接口(1)
    proxy('/api1', {
        target: 'http://www.baidu.com:80',
        changeOrigin: true,
    }),

    // 代理转发接口(2)
    proxy('/api2', {
        target: 'http://www.taobao.com:80',
        changeOrigin: true,
    })
]


/* browser-sync
 * 更多配置参考 http://www.browsersync.cn/docs/api/
*/
browserSync.init({
    // 配置server
    server: {
        // server的基础路径
        baseDir: './',
        // 使用中间件
        middleware: [...proxyArr]
    },
    // 定义host
    host: getIP(),
    // 设置端口
    port: 8099,
    // 项目启动时使用定义的host
    open: 'external',
    // 项目启动时打开的页面路径
    startPath: '/activities/index.html',
    // 修改那些文件的时候浏览器页面会自动刷新
    files: ['./**/*.html', './**/*.css', './**/*.js']
})

上一篇 下一篇

猜你喜欢

热点阅读