@@ -6,6 +6,8 @@ import Service from '../core/service';
6
6
import WebpackConfig from '../webpack' ;
7
7
import ActionFactory from './factory' ;
8
8
import { ICliOptions } from '../types' ;
9
+ import detect from 'detect-port' ;
10
+ import inquirer from 'inquirer' ;
9
11
10
12
class Dev extends ActionFactory {
11
13
private webpackConfig : WebpackConfig ;
@@ -92,13 +94,44 @@ class Dev extends ActionFactory {
92
94
this . service . commander . bindAction ( cmdName , this . action . bind ( this ) ) ;
93
95
}
94
96
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
+
95
123
protected async action ( cliOpts : ICliOptions ) {
96
124
process . title = 'ko-dev' ;
97
125
process . env . NODE_ENV = 'development' ;
98
126
this . service . freezeCliOptsWith ( cliOpts ) ;
99
127
const config = await this . generateConfig ( ) ;
128
+ const port = config . devServer ?. port as number ;
129
+ const newPort = ( await this . checkPort ( port ) ) as number ;
100
130
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
+ ) ;
102
135
await devServer . start ( ) ;
103
136
const exitProcess = ( callback ?: ( ) => void ) => ( ) => {
104
137
callback && callback ( ) ;
0 commit comments