@@ -6,6 +6,8 @@ import Service from '../core/service';
66import WebpackConfig from '../webpack' ;
77import ActionFactory from './factory' ;
88import { ICliOptions } from '../types' ;
9+ import detect from 'detect-port' ;
10+ import inquirer from 'inquirer' ;
911
1012class Dev extends ActionFactory {
1113 private webpackConfig : WebpackConfig ;
@@ -92,13 +94,44 @@ class Dev extends ActionFactory {
9294 this . service . commander . bindAction ( cmdName , this . action . bind ( this ) ) ;
9395 }
9496
97+ private async changePort ( newPort : number , port : number ) {
98+ const question = {
99+ type : 'confirm' ,
100+ name : 'changePort' ,
101+ message : `port: ${ port } has been used,use new port ${ newPort } instead?` ,
102+ default : true ,
103+ } ;
104+ const answer = await inquirer . prompt ( [ question ] ) ;
105+ if ( answer . changePort ) {
106+ return newPort ;
107+ }
108+ this . errorStdout ( `so sorry, ${ port } already in use!!` ) ;
109+ process . exit ( 0 ) ;
110+ }
111+
112+ private async checkPort ( port : number ) {
113+ const newPort = await detect ( port ) ;
114+ if ( newPort === port ) {
115+ return newPort ;
116+ }
117+ const isInteractive = process . stdout . isTTY ;
118+ if ( isInteractive ) {
119+ return this . changePort ( newPort , port ) ;
120+ }
121+ }
122+
95123 protected async action ( cliOpts : ICliOptions ) {
96124 process . title = 'ko-dev' ;
97125 process . env . NODE_ENV = 'development' ;
98126 this . service . freezeCliOptsWith ( cliOpts ) ;
99127 const config = await this . generateConfig ( ) ;
128+ const port = config . devServer ?. port as number ;
129+ const newPort = ( await this . checkPort ( port ) ) as number ;
100130 const compiler = Webpack ( config ) ;
101- const devServer = new WebpackDevServer ( config . devServer , compiler ) ;
131+ const devServer = new WebpackDevServer (
132+ { ...config . devServer , port : newPort } ,
133+ compiler
134+ ) ;
102135 await devServer . start ( ) ;
103136 const exitProcess = ( callback ?: ( ) => void ) => ( ) => {
104137 callback && callback ( ) ;
0 commit comments