1
- module . exports = { } ;
1
+ // based on https://github.com/webpack/webpack/blob/master/bin/webpack.js
2
+ module . exports = function promptForInstallation ( command , options ) {
3
+ const cp = require ( "child_process" ) ;
4
+ return new Promise ( ( resolve , reject ) => {
5
+ const executedCommand = cp . spawn ( command , options , {
6
+ stdio : "inherit" ,
7
+ shell : true
8
+ } ) ;
9
+
10
+ executedCommand . on ( "error" , error => {
11
+ reject ( error ) ;
12
+ } ) ;
13
+
14
+ executedCommand . on ( "exit" , code => {
15
+ if ( code === 0 ) {
16
+ resolve ( true ) ;
17
+ } else {
18
+ reject ( ) ;
19
+ }
20
+ } ) ;
21
+ } ) ;
22
+ }
23
+
24
+ let packageIsInstalled = false ;
25
+ try {
26
+ require . resolve ( package ) ;
27
+ packageIsInstalled = true ;
28
+ } catch ( err ) {
29
+ packageIsInstalled = false ;
30
+ }
31
+
32
+ if ( ! packageIsInstalled ) {
33
+ const path = require ( "path" ) ;
34
+ const fs = require ( "fs" ) ;
35
+ const readLine = require ( "readline" ) ;
36
+ const isYarn = fs . existsSync ( path . resolve ( process . cwd ( ) , "yarn.lock" ) ) ;
37
+
38
+ const packageManager = isYarn ? "yarn" : "npm" ;
39
+ const options = [ "install" , "-D" , package ] ;
40
+
41
+ if ( isYarn ) {
42
+ options [ 0 ] = "add" ;
43
+ }
44
+
45
+ const commandToBeRun = `${ packageManager } ${ options . join ( " " ) } ` ;
46
+
47
+ const question = `Would you like to install ${ packageIsInstalled } ? (That will run ${ commandToBeRun } ) (yes/NO)` ;
48
+
49
+ console . error ( `The CLI moved into a separate package: @webpack-cli/${ package } ` ) ;
50
+ const questionInterface = readLine . createInterface ( {
51
+ input : process . stdin ,
52
+ output : process . stdout
53
+ } ) ;
54
+ questionInterface . question ( question , answer => {
55
+ questionInterface . close ( ) ;
56
+ switch ( answer . toLowerCase ( ) ) {
57
+ case "y" :
58
+ case "yes" :
59
+ case "1" : {
60
+ runCommand ( packageManager , options )
61
+ . then ( result => {
62
+ return require ( `@webpack-cli/${ package } ` ) ; //eslint-disable-line
63
+ } )
64
+ . catch ( error => {
65
+ console . error ( error ) ;
66
+ process . exitCode = 1 ;
67
+ } ) ;
68
+ break ;
69
+ }
70
+ default : {
71
+ console . error (
72
+ "It needs to be installed alongside webpack to use the CLI"
73
+ ) ;
74
+ process . exitCode = 1 ;
75
+ break ;
76
+ }
77
+ }
78
+ } ) ;
79
+ } else {
80
+ require ( package ) ; // eslint-disable-line
81
+ }
0 commit comments