-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvite.config.ts
387 lines (363 loc) · 12 KB
/
vite.config.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
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/dist/ansi.js';
import {ConsoleAppender} from '@mburchard/bit-log/dist/appender/ConsoleAppender.js';
import {LogLevel} from '@mburchard/bit-log/dist/definitions.js';
import electronPath from 'electron';
import {build, defineConfig} from 'vite';
import {viteElectronConfig as cfg} from './project.config.js';
configureLogging({
appender: {
CONSOLE: {
Class: ConsoleAppender,
colored: true,
pretty: true,
},
},
root: {
appender: ['CONSOLE'],
level: 'DEBUG',
},
});
const log = useLog('vite.config', LogLevel.INFO);
export default defineConfig(({command, mode}): UserConfig => {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = mode;
}
const minify = mode === 'production' && false; // will be changed later, when minification is really wanted
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: './',
build: {
emptyOutDir: true,
minify,
outDir: cfg.output.app,
reportCompressedSize: false,
rollupOptions: {
input: rollupInput,
},
sourcemap: 'inline', // will decide later if we deploy without source maps
},
plugins: [
vitePluginMultiPage(),
{
name: 'vite-plugin-dev-server-url',
configureServer(server) {
server.httpServer?.once('listening', () => {
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),
],
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'],
},
},
};
});
function vitePluginElectron(command: 'serve' | 'build'): CustomPlugin {
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,
plugins: [
vitePluginElectronPreload(command),
vitePluginElectronHotReload(command),
],
build: {
emptyOutDir: true,
minify: false,
outDir: cfg.output.electron,
sourcemap: 'inline',
reportCompressedSize: false,
rollupOptions: {
external: id => id === 'electron' || id.includes('node:') || builtinModules.includes(id) ||
(!id.startsWith('@common/') && !path.join(id).includes(path.join(cfg.electron.root, 'src')) &&
/^[^./]/.test(id)),
input: {
main: path.resolve(__dirname, cfg.electron.root, 'src/main.ts'),
},
preserveEntrySignatures: 'strict',
output: {
format: 'esm',
entryFileNames: '[name].js',
preserveModules: true,
preserveModulesRoot: 'electron',
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));
},
};
}
function vitePluginElectronHotReload(command: 'serve' | 'build'): CustomPlugin {
let electronApp: ChildProcess | null = null;
let preloadPlugin: PluginOption | null | undefined = null;
let electronBuildReady = false;
let preloadBuildReady = false;
function cleanExit(code: number | null) {
log.info('Electron has been stopped');
setTimeout(() => {
log.info('stopping Vite process too');
process.exit(code);
}, 500);
}
function starteElectron() {
if (!electronBuildReady || !preloadBuildReady) {
return;
}
if (electronApp !== null) {
electronApp.removeListener('exit', cleanExit);
electronApp.kill('SIGINT');
electronApp = null;
}
electronApp = spawn(String(electronPath), ['--inspect', '.'], {
stdio: 'inherit',
});
electronApp.addListener('exit', cleanExit);
}
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') {
starteElectron();
}
});
}
if (command === 'serve') {
setupExitHandlers();
}
},
buildEnd() {
electronBuildReady = true;
if (command === 'serve') {
starteElectron();
}
},
};
}
function vitePluginElectronPreload(command: 'serve' | 'build'): CustomPlugin {
const eventEmitter = new EventEmitter();
let hasBeenBuild = 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') {
hasBeenBuild = true;
log.debug('Preload Script compiled and watching for changes');
eventEmitter.emit('build_end');
}
});
}
}
},
api: {
onBuildEnd(callback: () => void) {
eventEmitter.on('build_end', callback);
if (hasBeenBuild) {
callback();
}
},
},
};
}
function vitePluginMultiPage(): Plugin {
const contextMap = new Map<string, PageConfig>();
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.`);
}
const resolvedId = path.resolve(__dirname, cfg.app.root, `${currentPage}.html`);
log.debug(`resolve ID:`, id, 'to: ', resolvedId);
contextMap.set(resolvedId, pageConfig);
return resolvedId;
}
return id;
},
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 || '');
}
}
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 || '');
}
return template.replace('<%= PAGE_TITLE %>', pageConfig.title || '');
},
};
}