-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
507 lines (473 loc) · 17.2 KB
/
vite.config.ts
File metadata and controls
507 lines (473 loc) · 17.2 KB
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/**
* vite.config.ts
*
* @file Vite configuration with four custom plugins that orchestrate the full Electron build pipeline:
* multipage HTML resolution, Electron main process build, preload script compilation (CJS), and
* coordinated hot-reload during development. An EventEmitter synchronizes the build order, so Electron
* only starts once both the main process and preload builds have completed.
*
* @author Martin Burchard
*/
import type {ChildProcess} from 'node:child_process';
import type {Plugin, PluginOption, UserConfig} from 'vite';
import type {CustomPlugin, PageConfig} from './types/env.js';
import {spawn} from 'node:child_process';
import {EventEmitter} from 'node:events';
import fs from 'node:fs';
import {builtinModules} from 'node:module';
import path from 'node:path';
import process from 'node:process';
import {configureLogging, useLog} from '@mburchard/bit-log';
import {Ansi} from '@mburchard/bit-log/ansi';
import {ConsoleAppender} from '@mburchard/bit-log/appender/ConsoleAppender';
import electronBinary from 'electron';
import {build, defineConfig} from 'vite';
import {viteElectronConfig as cfg} from './project.config.js';
// ---- Logging ----
configureLogging({
appender: {
CONSOLE: {
Class: ConsoleAppender,
colored: true,
pretty: true,
},
},
root: {
appender: ['CONSOLE'],
level: 'DEBUG',
},
});
const log = useLog('vite.config', 'INFO');
// ---- App Frontend Configuration ----
export default defineConfig(({command, mode}): UserConfig => {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = mode;
}
const minify = mode === 'production';
const pageDevTools = Object.fromEntries(
Object.entries(cfg.app.pages).map(([pageName, page]) => [pageName, page.devTools === true]),
);
const pageDevToolsJson = JSON.stringify(pageDevTools);
log.info(`${Ansi.magenta(command === 'serve' ? 'Serving' : 'Building')} App Frontend`);
let rollupInput;
if (command === 'build') {
rollupInput = Object.fromEntries(
Object.entries(cfg.app.pages).map(([name]) => [
`${name}`,
`virtual:page:${name}.html`,
]),
);
log.debug('Rollup Input', rollupInput);
}
return {
root: cfg.app.root,
base: './',
define: {
'import.meta.env.VITE_APP_PAGE_DEVTOOLS': pageDevToolsJson,
},
build: {
emptyOutDir: true,
minify,
outDir: cfg.output.app,
reportCompressedSize: false,
rollupOptions: {
input: rollupInput,
},
sourcemap: 'inline',
},
plugins: [
vitePluginMultiPage(),
{
name: 'vite-plugin-dev-server-url',
configureServer(server) {
server.httpServer?.once('listening', () => {
/**
* Poll for the resolved dev server URL and store it in the environment.
*/
function checkServerURL() {
const serverURL = server.resolvedUrls?.local[0];
if (serverURL !== undefined) {
log.info('Serving App with Vite Dev Server on:', serverURL);
process.env.VITE_DEV_SERVER_URL = serverURL;
return;
}
log.debug('waiting for server url...');
setTimeout(checkServerURL, 1);
}
checkServerURL();
});
},
},
vitePluginElectron(command, pageDevToolsJson),
],
resolve: {
alias: {
'@assets': path.resolve(__dirname, cfg.app.root, 'assets'),
'@app': path.resolve(__dirname, cfg.app.root, 'src'),
'@common': path.resolve(__dirname, cfg.common.root, 'src'),
'@css': path.resolve(__dirname, cfg.app.root, 'css'),
},
},
server: {
watch: {
ignored: ['**/project.config.ts', '**/vite.config.ts', '**/vite-env.d.ts'],
},
},
};
});
// ---- Electron Main Process Plugin ----
/**
* Build the Electron main process as ESM with a preserved module structure. Nests the preload and hot-reload plugins
* as sub-plugins so the full backend pipeline runs within a single Vite build context.
*
* @param command - Vite command: 'serve' enables watch mode, 'build' produces a one-shot output.
* @param pageDevToolsJson - JSON string of per-page devTools flags injected as define constant.
* @returns A Vite plugin that triggers the Electron build inside its configResolved hook.
*/
function vitePluginElectron(command: 'serve' | 'build', pageDevToolsJson: string): CustomPlugin {
const electronPath = path.resolve(__dirname, cfg.electron.root, 'src');
log.debug('Electron Path:', electronPath);
const commonPath = path.resolve(__dirname, cfg.common.root, 'src');
log.debug('Common Path:', commonPath);
return {
name: 'vite-plugin-electron',
configResolved() {
if (command === 'serve') {
log.info(`Starting Electron in ${Ansi.cyan(process.env.NODE_ENV ?? '')} mode`);
} else {
log.info(`Building Electron for ${Ansi.cyan(process.env.NODE_ENV ?? '')}`);
}
build({
root: cfg.electron.root,
define: {
'import.meta.env.VITE_APP_PAGE_DEVTOOLS': pageDevToolsJson,
},
plugins: [
vitePluginElectronPreload(command),
vitePluginElectronHotReload(command),
],
build: {
emptyOutDir: true,
minify: false,
outDir: cfg.output.electron,
sourcemap: 'inline',
reportCompressedSize: false,
rollupOptions: {
external: (id) => {
const _path = path.normalize(id);
if (_path.startsWith(path.resolve(electronPath, 'common') + path.sep)) {
const msg = `Name conflict with common module and common folder in '${cfg.electron.root}'`;
log.error(msg);
throw new Error(msg);
}
if (_path.includes('@common')) {
log.debug('EXTERNAL CHECK:', _path, `-> ${Ansi.green('internal')}`);
return false;
}
const isExternal =
_path === 'electron' || _path.includes('node:') || builtinModules.includes(_path) ||
(!_path.includes(electronPath) && !_path.includes(commonPath) && /^[^./]/.test(id));
log.debug('EXTERNAL CHECK:', id, `: ${isExternal ? Ansi.red('external') : Ansi.green('internal')}`);
return isExternal;
},
input: {
main: path.resolve(electronPath, 'main.ts'),
},
preserveEntrySignatures: 'strict',
output: {
format: 'esm',
entryFileNames: (chunk) => {
if (!chunk.facadeModuleId) {
log.error('Skipping chunk with null facadeModuleId:', chunk);
return 'unknown.js';
}
const chunkPath = path.normalize(chunk.facadeModuleId);
const relativePath = path.relative(electronPath, chunkPath).replace(/\.ts$/, '.js');
log.debug('TEST:', chunkPath, '->', relativePath);
if (relativePath.startsWith('..') && chunkPath.startsWith(commonPath)) {
return path.join('common', path.relative(commonPath, chunkPath))
.replace(/\.ts$/, '.js');
}
return relativePath;
},
preserveModules: true,
exports: 'named',
},
},
...(command === 'serve' && {
watch: {
include: [`${cfg.common.root}/**/*.ts`, `${cfg.electron.root}/**/*.ts`],
},
}),
},
resolve: {
alias: {
'@common': path.resolve(__dirname, cfg.common.root, 'src'),
},
},
}).catch(reason => log.error('Electron Backend build failed:', reason));
},
};
}
// ---- Electron Hot Reload Plugin ----
/**
* Coordinate Electron process lifecycle during development. Waits for both the main process and preload builds to
* complete before spawning Electron and restarts it on later rebuilds. Registers SIGINT/SIGTERM handlers to
* ensure clean shutdown.
*
* @param command - Vite command: hot-reload logic only activates in 'serve' mode.
* @returns A Vite plugin that manages the Electron child process.
*/
function vitePluginElectronHotReload(command: 'serve' | 'build'): CustomPlugin {
let electronApp: ChildProcess | null = null;
let preloadPlugin: PluginOption | null | undefined = null;
let electronBuildReady = false;
let preloadBuildReady = false;
/**
* Handle Electron process exit by stopping the Vite dev server after a short delay.
*
* @param code - The exit code from the Electron process, or null if killed by signal.
*/
function cleanExit(code: number | null) {
log.info('Electron has been stopped');
setTimeout(() => {
log.info('stopping Vite process too');
process.exit(code);
}, 500);
}
/**
* Spawn or restart the Electron process once both main and preload builds are ready.
*/
function startElectron() {
if (!electronBuildReady || !preloadBuildReady) {
return;
}
if (electronApp !== null) {
electronApp.removeListener('exit', cleanExit);
electronApp.kill('SIGINT');
electronApp = null;
}
electronApp = spawn(String(electronBinary), ['--inspect', '.'], {
stdio: 'inherit',
});
electronApp.addListener('exit', cleanExit);
}
/**
* Register process signal handlers to cleanly terminate the Electron child process on shutdown.
*/
function setupExitHandlers() {
process.on('SIGINT', () => {
if (electronApp) {
log.info('Stopping Electron process before exiting Vite serve...');
electronApp.kill('SIGINT');
}
process.exit();
});
process.on('SIGTERM', () => {
if (electronApp) {
log.info('Stopping Electron process before exiting Vite serve...');
electronApp.kill('SIGTERM');
}
process.exit();
});
}
return {
name: 'vite-plugin-electron-hot-reload',
config(config, env) {
log.debug('configure vite-plugin-electron-hot-reload:', env);
preloadPlugin = config.plugins?.find(p =>
p != null && typeof p === 'object' && 'name' in p && p?.name === 'vite-plugin-electron-preload');
if (!preloadPlugin) {
throw new Error('vite-plugin-electron-preload not found');
}
if (preloadPlugin && 'api' in preloadPlugin) {
preloadPlugin.api.onBuildEnd(() => {
preloadBuildReady = true;
if (command === 'serve') {
startElectron();
}
});
}
if (command === 'serve') {
setupExitHandlers();
}
},
buildEnd() {
electronBuildReady = true;
if (command === 'serve') {
startElectron();
}
},
};
}
// ---- Electron Preload Plugin ----
/**
* Compile the preload script as a CommonJS bundle. Runs as a nested build inside the Electron plugin's closeBundle
* hook. In serve mode, sets up a file watcher and emits 'build_end' events consumed by the hot-reload plugin.
*
* @param command - Vite command: 'serve' enables watch mode with rebuild notifications.
* @returns A Vite plugin with an `api.onBuildEnd` callback for cross-plugin coordination.
*/
function vitePluginElectronPreload(command: 'serve' | 'build'): CustomPlugin {
const eventEmitter = new EventEmitter();
let hasBeenBuilt = false;
const entryPoint = path.resolve(__dirname, cfg.preload.root, 'src', 'preload.ts');
return {
name: 'vite-plugin-electron-preload',
async closeBundle() {
log.debug('Compiling Preload Script...');
const watcher = await build({
configFile: false,
root: cfg.preload.root,
build: {
emptyOutDir: false,
lib: {
entry: entryPoint,
formats: ['cjs'],
},
minify: false,
outDir: cfg.output.electron,
reportCompressedSize: false,
rollupOptions: {
input: entryPoint,
external: id => id === 'electron' || id.includes('node:') || builtinModules.includes(id),
output: {
entryFileNames: '[name].js',
format: 'cjs',
},
},
sourcemap: 'inline',
...(command === 'serve' && {
watch: {
include: [`${cfg.common.root}/**/*.ts`, `${cfg.preload.root}/**/*.ts`],
},
}),
},
resolve: {
alias: {
'@common': path.resolve(__dirname, cfg.common.root, 'src'),
},
},
});
if (command === 'serve') {
if ('on' in watcher) {
watcher.on('event', (event: any) => {
if (event.code === 'BUNDLE_END') {
hasBeenBuilt = true;
log.debug('Preload Script compiled and watching for changes');
eventEmitter.emit('build_end');
}
});
}
}
},
api: {
/**
* Register a callback that fires after each successful preload build.
*
* @param callback - Invoked once the preload bundle is ready.
*/
onBuildEnd(callback: () => void) {
eventEmitter.on('build_end', callback);
if (hasBeenBuilt) {
callback();
}
},
},
};
}
// ---- Multi-Page Plugin ----
/**
* Resolve virtual `virtual:page:NAME.html` modules to real HTML templates, inject script modules and template
* variables (`PAGE_TITLE`, `PAGE`). Supports both build mode (rollup input) and dev server (transformIndexHtml).
*
* @returns A Vite plugin handling multipage HTML resolution and transformation.
*/
function vitePluginMultiPage(): Plugin {
const contextMap = new Map<string, PageConfig>();
/**
* Read an HTML template from disk and inject the page's script modules before `</body>`. In development mode,
* the Vite client script is also injected into `<head>`.
*
* @param pageConfig - The page configuration containing template path and module list.
* @returns The processed HTML string, or null if the template could not be loaded.
*/
function loadTemplate(pageConfig: PageConfig | undefined | null): string | null {
const templatePath = pageConfig?.template ?
path.resolve(__dirname, cfg.app.root, 'templates', pageConfig.template) :
path.resolve(__dirname, cfg.app.root, 'index.html');
try {
const fileContent = fs.readFileSync(templatePath, 'utf-8');
log.debug('HTML template loaded from', templatePath, '->', fileContent);
if (!pageConfig?.modules || pageConfig.modules.length === 0) {
log.warn('No modules found for pageConfig:', pageConfig);
return fileContent;
}
let result = fileContent;
if (process.env.NODE_ENV === 'development') {
// noinspection HtmlUnknownTarget
result = result.replace('head>', 'head>\n<script type="module" src="/@vite/client"></script>');
}
const modules = pageConfig.modules
.map(module => ` <script type="module" src="${module.startsWith('./') ? module : `./${module}`}"></script>`)
.join('\n');
result = result.replace('</body>', `${modules}\n</body>`);
log.debug('HTML template with injected modules:', result);
return result;
} catch (e) {
log.error('Failed to load template for page:', templatePath, e);
return null;
}
}
return {
name: 'vite-plugin-multi-page',
load(id) {
const pageConfig = contextMap.has(id) ? contextMap.get(id) : null;
if (pageConfig) {
log.debug(`vite-plugin-multi-page.load(${Ansi.cyan(id)})`);
return loadTemplate(contextMap.get(id) ?? null);
}
},
resolveId(id) {
const match = id.match(/^virtual:page:(.+)\.html$/);
if (match) {
const currentPage = match[1];
const pageConfig = cfg.app.pages[currentPage];
if (!pageConfig) {
throw new Error(`No page config available for ${Ansi.cyan(currentPage)}, please check your configuration.`);
}
pageConfig.id = currentPage;
const resolvedId = path.resolve(__dirname, cfg.app.root, `${currentPage}.html`);
log.debug(`resolve ID:`, id, 'to: ', resolvedId);
contextMap.set(resolvedId, pageConfig);
return resolvedId;
}
},
transformIndexHtml(html, ctx) {
if (ctx.filename) {
const filename = path.join(ctx.filename);
const pageConfig = contextMap.has(filename) ? contextMap.get(filename) : null;
if (pageConfig) {
return html.replace('<%= PAGE_TITLE %>', pageConfig.title || '').replace('<%= PAGE %>', pageConfig.id ?? '');
}
}
if (!ctx.originalUrl) {
log.warn('Should not reach this point');
return html;
}
const pageName = ctx.originalUrl?.split('/').filter(Boolean)[0] ?? 'main';
log.debug('pageName:', pageName);
const pageConfig = cfg.app.pages[pageName];
log.debug('pageConfig:', pageConfig);
if (!pageConfig) {
log.error('no page config found for', pageName);
return html;
}
const template = loadTemplate(pageConfig);
if (!template) {
return html.replace('<%= PAGE_TITLE %>', pageConfig.title ?? '').replace('<%= PAGE %>', pageName);
}
return template.replace('<%= PAGE_TITLE %>', pageConfig.title ?? '').replace('<%= PAGE %>', pageName);
},
};
}