UNPKG

2.73 kBJavaScriptView Raw
1var path = require('path');
2var chalk = require('chalk');
3var parse = require('url-parse');
4var express = require('express');
5var proxy = require('http-proxy-middleware');
6var WebpackDevServer = require('webpack-dev-server');
7
8var WebpackDevConfig = require('../config/webpack.config.dev');
9
10// var openBrowser = require('./openBrowser');
11var clearConsole = require('./clearConsole');
12var setupCompiler = require('./setupCompiler');
13var applyProxyModdileware = require('./applyProxyModdileware');
14
15var isInteractive = process.stdout.isTTY;
16
17function runDevServer(config, dllConfig) {
18 var server = config.server;
19 var protocol = server.protocol;
20 var host = server.host;
21 var port = server.port;
22 var publicPath = parse(config.output.publicPath);
23 var webpackConfig = WebpackDevConfig(config, dllConfig);
24 var compiler = setupCompiler(webpackConfig, {
25 host: host,
26 port: port,
27 protocol: protocol,
28 });
29 var devServer = new WebpackDevServer(compiler, Object.assign({
30 disableHostCheck: true,
31 contentBase: [
32 config.context,
33 ],
34 compress: true,
35 inline: true,
36 hot: true,
37 quiet: true,
38 noInfo: true,
39 clientLogLevel: 'none',
40 watchContentBase: false,
41 watchOptions: {
42 ignored: /node_modules/
43 },
44 publicPath: config.output.publicPath,
45 https: protocol === 'https',
46 headers: {
47 // fix CORS policy
48 'Access-Control-Allow-Origin': '*',
49 },
50 host: host,
51 port: port,
52 overlay: true,
53 historyApiFallback: false,
54 setup: function (app) {
55 // fix client proxy to webpack dev server not work problem
56 // webpack dev server could not recognize wrong host
57 app.use(proxy(function (pathname, req) {
58 var parsedUrl = parse(req.url);
59 // TODO perfect rule
60 if (parsedUrl.origin != 'null') {
61 return true;
62 }
63 return false;
64 }, { target: config.output.publicUrl }));
65 // server dll assets
66 config.chunks.forEach(function (chunk) {
67 var dll = path.resolve(config.output.dll, chunk.name);
68 app.use(publicPath.pathname, express.static(dll, {
69 setHeaders: function (res) {
70 // fix CORS policy
71 res.header('Access-Control-Allow-Origin', '*');
72 },
73 }));
74 });
75 },
76 }, config.server.original));
77
78 applyProxyModdileware(devServer, config);
79
80 devServer.listen(port, function (err) {
81 if (err) {
82 console.log(err);
83 return;
84 }
85
86 if (isInteractive) {
87 clearConsole();
88 }
89 console.log(chalk.cyan('Starting the development server...'));
90 console.log();
91
92 // TODO
93 // openBrowser(protocol + '://' + host + ':' + port + '/');
94 });
95}
96
97module.exports = runDevServer;