dev-server.js 2.2 KB
Newer Older
B
BingBlog 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
process.env.NODE_ENV = 'dev';
let devPort = 8999;
let opn = require('opn');
let express = require('express');
let webpack = require('webpack');
let proxyMiddleware = require('http-proxy-middleware');
let webpackConfig = require('./webpack.dev.config');
let autoresponse = require('autoresponse');
let path = require('path');

let port = devPort;
let autoOpenBrowser = false;

let app = express();
let compiler = webpack(webpackConfig);

let devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    disableHostCheck: true,
    quiet: false,
    noInfo: false,
    stats: {
        colors: true
    },
    headers: {'Access-Control-Allow-Origin': '*'}
});

let hotMiddleware = require('webpack-hot-middleware')(compiler, {
    heartbeat: 2000
});
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
        hotMiddleware.publish({
            action: 'reload'
        });
        cb();
    });
});

41 42 43 44 45 46
// autoresponse
let AutoresponseMatchs = ['data'];
let matchsReg = new RegExp(AutoresponseMatchs.join('\|'));
let excludeReg = /\.(html|js|map)$/;
let isAutoresponseRequest = (path) => {
    return !excludeReg.test(path) && matchsReg.test(path);
B
BingBlog 已提交
47
}
48

B
BingBlog 已提交
49 50 51 52 53
app.use(autoresponse({
    logLevel: 'debug',
    root: path.dirname(__dirname),
    rules: [
        {
54 55
            match: isAutoresponseRequest,
            method: ['get', 'post', , 'delete']
B
BingBlog 已提交
56
        }
57
    ]
B
BingBlog 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
}));

// serve webpack bundle output
app.use(devMiddleware);

// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware);

let uri = 'http://localhost:' + port;

let _resolve;
let readyPromise = new Promise(resolve => {
    _resolve = resolve;
});

console.log('> Starting dev server...');
devMiddleware.waitUntilValid(() => {
    console.log('> Listening at ' + uri + '\n');
    // when env is testing, don't need open it
    if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
        opn(uri);
    }

    _resolve();
});

let server = app.listen(port);

module.exports = {
    ready: readyPromise,
    close() {
        server.close();
    }
};