1
+ /* eslint-disable @typescript-eslint/camelcase */
2
+ /**
3
+ * 主进程 webpack 构建
4
+ * electron 启动交给 electron-connect
5
+ */
6
+ const path = require ( 'path' ) ;
7
+ const child_process = require ( 'child_process' ) ;
8
+ const electron = require ( 'electron' ) ;
9
+ const webpack = require ( 'webpack' ) ;
10
+ const chalk = require ( 'chalk' ) ;
11
+ const ora = require ( 'ora' ) ;
12
+ const wait_on = require ( 'wait-on' ) ;
13
+ const argv = require ( 'minimist' ) ( process . argv . slice ( 2 ) ) ;
14
+ const config_factory = require ( './webpack.main' ) ;
15
+ require ( 'dotenv' ) . config ( { path : path . join ( __dirname , '../src/render/.env' ) } ) ;
16
+
17
+ const root = path . join ( __dirname , '..' ) ;
18
+ const main = process . env [ 'npm_package_main' ] ;
19
+ const { env, port = process . env . PORT , watch } = argv ;
20
+ const spinner = ora ( 'Electron webpack build...' ) ;
21
+ const TAG = 'scripts/main-build.js' ;
22
+ let watching = null ;
23
+ let child = null ;
24
+
25
+ const compiler = webpack ( config_factory ( env ) ) ;
26
+ compiler . hooks . afterCompile . tap ( TAG , ( ) => {
27
+ spinner . stop ( ) ;
28
+ if ( watch ) { // 开发模式
29
+ if ( child ) { process . kill ( child . pid , 'SIGINT' ) ; }
30
+ child = child_process . spawn (
31
+ electron ,
32
+ [ path . join ( root , main ) ] ,
33
+ { stdio : 'inherit' , }
34
+ ) ;
35
+ }
36
+ } ) ;
37
+ compiler . hooks . beforeCompile . tap ( TAG , ( ) => {
38
+ spinner . start ( ) ;
39
+ } ) ;
40
+
41
+ function compileHandle ( err , stats ) {
42
+ if ( err ) {
43
+ // err 对象将只包含与webpack相关的问题,例如错误配置等
44
+ console . log ( TAG , chalk . red ( '💥 Electron webpack 相关报错' ) ) ;
45
+ console . log ( err ) ;
46
+
47
+ // 关闭 wepback 监听
48
+ watching && watching . close ( ( ) => console . log ( TAG , 'Watching Ended.' ) ) ;
49
+ process . exit ( 1 ) ;
50
+ } else if ( stats . hasErrors ( ) ) {
51
+ // webpack 编译报错
52
+ const json = stats . toJson ( 'errors-only' ) ;
53
+ console . log ( TAG , json . errors ) ;
54
+ console . log ( TAG , chalk . red ( '💥 Electron 构建报错' ) ) ;
55
+ } else {
56
+ console . log ( TAG , chalk . green ( 'Electron webpack 构建完成' ) ) ;
57
+ }
58
+ }
59
+
60
+ if ( watch ) { // 开发模式
61
+ const opts = {
62
+ resources : [ `http://localhost:${ port } ` ] , // PORT === port
63
+ interval : 900 , // poll interval in ms, default 250ms
64
+ log : false ,
65
+ } ;
66
+
67
+ // 等待 webpack-dev-server 启动后启动 electron
68
+ wait_on ( opts , function ( err ) {
69
+ if ( err ) {
70
+ console . log ( err ) ;
71
+ process . exit ( 1 ) ;
72
+ }
73
+ // once here, all resources are available
74
+ watching = compiler . watch ( {
75
+ ignored : / b u n d l e \. j s ( \. m a p ) ? / ,
76
+ } , compileHandle ) ;
77
+ } ) ;
78
+ } else { // 构建模式
79
+ compiler . run ( compileHandle ) ;
80
+ }
0 commit comments