/
WebpackPlugin.ts
449 lines (395 loc) · 14.5 KB
/
WebpackPlugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/* eslint "no-console": "off" */
import { asyncOra } from '@electron-forge/async-ora';
import PluginBase from '@electron-forge/plugin-base';
import { ForgeConfig } from '@electron-forge/shared-types';
import Logger, { Tab } from '@electron-forge/web-multi-logger';
import { ChildProcess } from 'child_process';
import debug from 'debug';
import fs from 'fs-extra';
import merge from 'webpack-merge';
import path from 'path';
import webpack, { Configuration } from 'webpack';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackDevMiddleware from 'webpack-dev-middleware';
import express from 'express';
import http from 'http';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import once from './util/once';
import { WebpackPluginConfig, WebpackPluginEntryPoint, WebpackPreloadEntryPoint } from './Config';
const d = debug('electron-forge:plugin:webpack');
const DEFAULT_PORT = 3000;
const DEFAULT_LOGGER_PORT = 9000;
export default class WebpackPlugin extends PluginBase<WebpackPluginConfig> {
name = 'webpack';
private isProd = false;
private projectDir!: string;
private baseDir!: string;
private watchers: webpack.Compiler.Watching[] = [];
private servers: http.Server[] = [];
private loggers: Logger[] = [];
private port = DEFAULT_PORT;
private loggerPort = DEFAULT_LOGGER_PORT;
constructor(c: WebpackPluginConfig) {
super(c);
if (c.port) {
if (this.isValidPort(c.port)) {
this.port = c.port;
}
}
if (c.LoggerPort) {
if (this.isValidPort(c.LoggerPort)) {
this.loggerPort = c.LoggerPort;
}
}
this.startLogic = this.startLogic.bind(this);
this.getHook = this.getHook.bind(this);
}
private isValidPort = (port: number) => {
if (port < 1024) {
throw new Error(`Cannot specify port (${port}) below 1024, as they are privileged`);
} else if (port > 65535) {
throw new Error(`Port specified (${port}) is not a valid TCP port.`);
} else {
return true;
}
}
private resolveConfig = (config: Configuration | string) => {
// eslint-disable-next-line import/no-dynamic-require, global-require
if (typeof config === 'string') return require(path.resolve(path.dirname(this.baseDir), config)) as Configuration;
return config;
}
private exitHandler = (options: { cleanup?: boolean; exit?: boolean }, err?: Error) => {
d('handling process exit with:', options);
if (options.cleanup) {
for (const watcher of this.watchers) {
d('cleaning webpack watcher');
watcher.close(() => {});
}
this.watchers = [];
for (const server of this.servers) {
d('cleaning http server');
server.close();
}
this.servers = [];
for (const logger of this.loggers) {
d('stopping logger');
logger.stop();
}
this.loggers = [];
}
if (err) console.error(err.stack);
if (options.exit) process.exit();
}
init = (dir: string) => {
this.projectDir = dir;
this.baseDir = path.resolve(dir, '.webpack');
d('hooking process events');
process.on('exit', _code => this.exitHandler({ cleanup: true }));
process.on('SIGINT' as NodeJS.Signals, _signal => this.exitHandler({ exit: true }));
}
private loggedOutputUrl = false;
getHook(name: string) {
switch (name) {
case 'prePackage':
this.isProd = true;
return async () => {
await fs.remove(this.baseDir);
await this.compileMain();
await this.compileRenderers();
};
case 'postStart':
return async (_: any, child: ChildProcess) => {
if (!this.loggedOutputUrl) {
console.info(`\n\nWebpack Output Available: ${'http://localhost:'.cyan}${this.loggerPort}\n`);
this.loggedOutputUrl = true;
}
d('hooking electron process exit');
child.on('exit', () => {
if ((child as any).restarted) return;
this.exitHandler({ cleanup: true, exit: true });
});
};
case 'resolveForgeConfig':
return this.resolveForgeConfig;
case 'packageAfterCopy':
return this.packageAfterCopy;
default:
return null;
}
}
resolveForgeConfig = async (forgeConfig: ForgeConfig) => {
if (!forgeConfig.packagerConfig) {
forgeConfig.packagerConfig = {};
}
if (forgeConfig.packagerConfig.ignore) {
console.error(`You have set packagerConfig.ignore, the electron forge webpack plugin normally sets this automatically.
Your packaged app may be larger than expected if you dont ignore everything other than the '.webpack' folder`.red);
return forgeConfig;
}
forgeConfig.packagerConfig.ignore = (file: string) => {
if (!file) return false;
return !/^[/\\]\.webpack($|[/\\]).*$/.test(file);
};
return forgeConfig;
}
packageAfterCopy = async (_: any, buildPath: string) => {
const pj = await fs.readJson(path.resolve(this.projectDir, 'package.json'));
delete pj.config.forge;
pj.devDependencies = {};
pj.dependencies = {};
pj.optionalDependencies = {};
pj.peerDependencies = {};
await fs.writeJson(
path.resolve(buildPath, 'package.json'),
pj,
{
spaces: 2,
},
);
await fs.mkdirp(path.resolve(buildPath, 'node_modules'));
}
// eslint-disable-next-line max-len
rendererEntryPoint = (entryPoint: WebpackPluginEntryPoint, inRendererDir: boolean, basename: string): string => {
if (this.isProd) {
return `\`file://$\{require('path').resolve(__dirname, '..', '${inRendererDir ? 'renderer' : '.'}', '${entryPoint.name}', '${basename}')}\``;
}
const baseUrl = `http://localhost:${this.port}/${entryPoint.name}`;
if (basename !== 'index.html') {
return `'${baseUrl}/${basename}'`;
}
return `'${baseUrl}'`;
}
toEnvironmentVariable = (entryPoint: WebpackPluginEntryPoint, preload = false): string => {
const suffix = preload ? '_PRELOAD_WEBPACK_ENTRY' : '_WEBPACK_ENTRY';
return `${entryPoint.name.toUpperCase().replace(/ /g, '_')}${suffix}`;
}
getPreloadDefine = (entryPoint: WebpackPluginEntryPoint): string => {
if (entryPoint.preload) {
if (this.isProd) {
return `require('path').resolve(__dirname, '../renderer', '${entryPoint.name}', 'preload.js')`;
}
return `'${path.resolve(this.baseDir, 'renderer', entryPoint.name, 'preload.js').replace(/\\/g, '\\\\')}'`;
}
// If this entry-point has no configured preload script just map this constant to `undefined`
// so that any code using it still works. This makes quick-start / docs simpler.
return 'undefined';
}
getDefines = (inRendererDir = true) => {
const defines: { [key: string]: string; } = {};
if (!this.config.renderer.entryPoints || !Array.isArray(this.config.renderer.entryPoints)) {
throw new Error('Required config option "renderer.entryPoints" has not been defined');
}
for (const entryPoint of this.config.renderer.entryPoints) {
const entryKey = this.toEnvironmentVariable(entryPoint);
if (entryPoint.html) {
defines[entryKey] = this.rendererEntryPoint(entryPoint, inRendererDir, 'index.html');
} else {
defines[entryKey] = this.rendererEntryPoint(entryPoint, inRendererDir, 'index.js');
}
defines[`process.env.${entryKey}`] = defines[entryKey];
const preloadDefineKey = this.toEnvironmentVariable(entryPoint, true);
defines[preloadDefineKey] = this.getPreloadDefine(entryPoint);
defines[`process.env.${preloadDefineKey}`] = defines[preloadDefineKey];
}
return defines;
}
getMainConfig = async () => {
const mainConfig = this.resolveConfig(this.config.mainConfig);
if (!mainConfig.entry) {
throw new Error('Required config option "entry" has not been defined');
}
const defines = this.getDefines();
return merge.smart({
devtool: 'source-map',
target: 'electron-main',
mode: this.isProd ? 'production' : 'development',
output: {
path: path.resolve(this.baseDir, 'main'),
filename: 'index.js',
libraryTarget: 'commonjs2',
},
plugins: [
new webpack.DefinePlugin(defines),
],
node: {
__dirname: false,
__filename: false,
},
resolve: {
modules: [
path.resolve(path.dirname(this.baseDir), './'),
path.resolve(path.dirname(this.baseDir), 'node_modules'),
path.resolve(__dirname, '..', 'node_modules'),
],
},
}, mainConfig || {});
}
getPreloadRendererConfig = async (
parentPoint: WebpackPluginEntryPoint,
entryPoint: WebpackPreloadEntryPoint,
) => {
const rendererConfig = this.resolveConfig(this.config.renderer.config);
const prefixedEntries = entryPoint.prefixedEntries || [];
return merge.smart({
devtool: 'inline-source-map',
target: 'electron-renderer',
mode: this.isProd ? 'production' : 'development',
entry: prefixedEntries.concat([
entryPoint.js,
]),
output: {
path: path.resolve(this.baseDir, 'renderer', parentPoint.name),
filename: 'preload.js',
},
node: {
__dirname: false,
__filename: false,
},
}, rendererConfig);
}
getRendererConfig = async (entryPoints: WebpackPluginEntryPoint[]) => {
const rendererConfig = this.resolveConfig(this.config.renderer.config);
const entry: webpack.Entry = {};
for (const entryPoint of entryPoints) {
const prefixedEntries = entryPoint.prefixedEntries || [];
entry[entryPoint.name] = prefixedEntries
.concat([entryPoint.js])
.concat(this.isProd || !entryPoint.html ? [] : ['webpack-hot-middleware/client']);
}
const defines = this.getDefines(false);
return merge.smart({
entry,
devtool: 'inline-source-map',
target: 'electron-renderer',
mode: this.isProd ? 'production' : 'development',
output: {
path: path.resolve(this.baseDir, 'renderer'),
filename: '[name]/index.js',
globalObject: 'self',
},
node: {
__dirname: false,
__filename: false,
},
plugins: entryPoints.filter(entryPoint => Boolean(entryPoint.html))
.map(entryPoint => new HtmlWebpackPlugin({
title: entryPoint.name,
template: entryPoint.html,
filename: `${entryPoint.name}/index.html`,
chunks: [entryPoint.name].concat(entryPoint.additionalChunks || []),
})).concat([new webpack.DefinePlugin(defines)])
.concat(this.isProd ? [] : [new webpack.HotModuleReplacementPlugin()]),
}, rendererConfig);
}
compileMain = async (watch = false, logger?: Logger) => {
let tab: Tab;
if (logger) {
tab = logger.createTab('Main Process');
}
await asyncOra('Compiling Main Process Code', async () => {
await new Promise(async (resolve, reject) => {
const compiler = webpack(await this.getMainConfig());
const [onceResolve, onceReject] = once(resolve, reject);
const cb: webpack.ICompiler.Handler = (err, stats) => {
if (tab) {
tab.log(stats.toString({
colors: true,
}));
}
if (err) return onceReject(err);
if (!watch && stats.hasErrors()) {
return onceReject(new Error(`Compilation errors in the main process: ${stats.toString()}`));
}
return onceResolve();
};
if (watch) {
this.watchers.push(compiler.watch({}, cb));
} else {
compiler.run(cb);
}
});
});
}
compileRenderers = async (watch = false) => { // eslint-disable-line @typescript-eslint/no-unused-vars, max-len
await asyncOra('Compiling Renderer Template', async () => {
await new Promise(async (resolve, reject) => {
webpack(await this.getRendererConfig(this.config.renderer.entryPoints))
.run((err, stats) => {
if (err) return reject(err);
if (!watch && stats.hasErrors()) {
return reject(new Error(`Compilation errors in the renderer: ${stats.toString()}`));
}
return resolve();
});
});
});
for (const entryPoint of this.config.renderer.entryPoints) {
if (entryPoint.preload) {
await asyncOra(`Compiling Renderer Preload: ${entryPoint.name}`, async () => {
await new Promise(async (resolve, reject) => {
webpack(await this.getPreloadRendererConfig(entryPoint, entryPoint.preload!))
.run((err) => {
if (err) return reject(err);
return resolve();
});
});
});
}
}
}
launchDevServers = async (logger: Logger) => {
await asyncOra('Launch Dev Servers', async () => {
const tab = logger.createTab('Renderers');
const config = await this.getRendererConfig(this.config.renderer.entryPoints);
const compiler = webpack(config);
const server = webpackDevMiddleware(compiler, {
logger: {
log: tab.log.bind(tab),
info: tab.log.bind(tab),
error: tab.log.bind(tab),
warn: tab.log.bind(tab),
},
publicPath: '/',
hot: true,
historyApiFallback: true,
} as any);
const app = express();
app.use(server);
app.use(webpackHotMiddleware(compiler));
this.servers.push(app.listen(this.port));
});
await asyncOra('Compiling Preload Scripts', async () => {
for (const entryPoint of this.config.renderer.entryPoints) {
if (entryPoint.preload) {
await new Promise(async (resolve, reject) => {
const tab = logger.createTab(`${entryPoint.name} - Preload`);
const [onceResolve, onceReject] = once(resolve, reject);
const cb: webpack.ICompiler.Handler = (err, stats) => {
tab.log(stats.toString({
colors: true,
}));
if (err) return onceReject(err);
return onceResolve();
};
this.watchers.push(webpack(await this.getPreloadRendererConfig(
entryPoint,
entryPoint.preload!,
)).watch({}, cb));
});
}
}
});
}
private alreadyStarted = false;
async startLogic(): Promise<false> {
if (this.alreadyStarted) return false;
this.alreadyStarted = true;
await fs.remove(this.baseDir);
const logger = new Logger(this.loggerPort);
this.loggers.push(logger);
await this.compileMain(true, logger);
await this.launchDevServers(logger);
await logger.start();
return false;
}
}