const uri = require ( 'url' ) ; const WebpackDevServer = require ( 'webpack-dev-server' ) ; const httpProxy = require ( 'http-proxy' ) ; const modifyIndexHtmlMiddleware = require ( './modifyResponse' ) ; const initCompiler = require ( './initCompiler' ) ; const argv = require ( 'optimist' ) . usage ( 'Usage: $0 -target [url] -config [config]' ) . demand ( [ 'target' , 'config' ] ) . argv ; const target = argv . target . startsWith ( 'https' ) ? argv . target : `https://${ argv . target }` ; const urlObj = uri . parse ( target ) ; const webpackConfig = require ( argv . config ) ; if ( ! urlObj . host ) { console . error ( 'invalid URL: ' + target ) ; return ; } const PROXY_TARGET = urlObj . host ; const ROOT = '/web' ; const PORT = 8080 ; const compiler = initCompiler ( { webpackConfig } ) ; compiler . callWhenReady ( function ( ) { console . log ( '\x1b[33m' , `DevServer is ready to serve: https://localhost:${ PORT }/web/` , '\x1b[0m' ) ; } ) ; function getTargetOptions ( ) { return { target : 'https://' + PROXY_TARGET , secure : false , changeOrigin : true , xfwd : true , } ; } const devServer = new WebpackDevServer ( { proxy : { '/web/config.*' : getTargetOptions ( ) , '/v1/*' : getTargetOptions ( ) , } , static : { serveIndex : false , publicPath : ROOT + '/app' , } , server : { type : 'https' , } , host : '0.0.0.0' , port : PORT , allowedHosts : 'auto' , client : { overlay : false , } , devMiddleware : { stats : 'minimal' , } , hot : true , headers : { 'X-Custom-Header' : 'yes' } , } , compiler . webpackCompiler ) ; const proxyServer = httpProxy . createProxyServer ( ) ; process . on ( 'SIGINT' , ( ) => { proxyServer . close ( ) ; } ) ; function serveIndexHtml ( req , res ) { if ( req . headers [ 'accept-encoding' ] ) { req . headers [ 'accept-encoding' ] = req . headers [ 'accept-encoding' ] . replace ( 'gzip, ' , '' ) . replace ( ', gzip,' , ',' ) . replace ( 'gzip' , '' ) ; } function handleRequest ( ) { proxyServer . web ( req , res , getTargetOptions ( ) ) ; } if ( ! compiler . isLocalIndexHtmlReady ( ) ) { compiler . callWhenReady ( handleRequest ) ; } else { handleRequest ( ) ; } } devServer . start ( ) . then ( ( ) => { devServer . app . use ( modifyIndexHtmlMiddleware ( compiler ) ) ; devServer . app . get ( '/*' , serveIndexHtml ) ; devServer . server . on ( 'upgrade' , ( req , socket ) => { if ( req . url === '/ws' ) { return ; } console . log ( 'proxying ws' , req . url ) ; proxyServer . ws ( req , socket , { target : 'wss://' + PROXY_TARGET , secure : false , } ) ; } ) ; } ) ;