Browse Source

WIP: Electron asset path and renderer build fixes

- Configure Vite renderer build for relative asset paths and explicit asset directory
- Remove baseURLForDataURL (caused Electron crash)
- Add debug logging for asset/network requests
- App now loads and assets are found, but some stylesheets may still be missing

Next: investigate CSS chunking/code splitting for Electron reliability.
streamline-attempt
Matthew Raymer 2 weeks ago
parent
commit
1c998a777f
  1. 2
      .gitignore
  2. 69
      src/electron/main.ts
  3. 11
      temp.har
  4. 6
      vite.config.electron.renderer.mts

2
.gitignore

@ -54,5 +54,5 @@ build_logs/
# PWA icon files generated by capacitor-assets # PWA icon files generated by capacitor-assets
icons icons
*.log
android/app/src/main/res/ android/app/src/main/res/

69
src/electron/main.ts

@ -19,7 +19,7 @@ const logger = {
// Check if running in dev mode // Check if running in dev mode
const isDev = process.argv.includes("--inspect"); const isDev = process.argv.includes("--inspect");
function createWindow(): void { async function createWindow(): Promise<void> {
// Add before createWindow function // Add before createWindow function
const preloadPath = app.isPackaged const preloadPath = app.isPackaged
? path.join(app.getAppPath(), "dist-electron", "preload.js") ? path.join(app.getAppPath(), "dist-electron", "preload.js")
@ -62,40 +62,36 @@ function createWindow(): void {
// Always open DevTools for now // Always open DevTools for now
mainWindow.webContents.openDevTools(); mainWindow.webContents.openDevTools();
// Intercept requests to fix asset paths // Intercept requests to robustly fix asset paths for Electron
mainWindow.webContents.session.webRequest.onBeforeRequest( mainWindow.webContents.session.webRequest.onBeforeRequest(
{ { urls: ["*://*/*"] },
urls: [
"file://*/*/assets/*",
"file://*/assets/*",
"file:///assets/*", // Catch absolute paths
"<all_urls>", // Catch all URLs as a fallback
],
},
(details, callback) => { (details, callback) => {
let url = details.url; const url = details.url;
logger.log('[main.ts] Intercepted request:', url);
// Handle paths that don't start with file://
if (!url.startsWith("file://") && url.includes("/assets/")) { // Match both file:///assets/... and /assets/...
url = `file://${path.join(__dirname, "www", url)}`; const assetMatch = url.match(/(?:file:\/\/\/|file:\/\/|https?:\/\/[^\/]+)?\/assets\/(.+)/);
} if (assetMatch) {
const assetRelPath = assetMatch[1];
const assetAbsPath = path.join(app.getAppPath(), "dist-electron", "www", "assets", assetRelPath);
logger.log('[main.ts] Asset request detected:', {
originalUrl: url,
assetRelPath,
assetAbsPath,
exists: fs.existsSync(assetAbsPath)
});
// Handle absolute paths starting with /assets/ if (fs.existsSync(assetAbsPath)) {
if (url.includes("/assets/") && !url.includes("/www/assets/")) { const newUrl = `file://${assetAbsPath}`;
const baseDir = url.includes("dist-electron") logger.log('[main.ts] Redirecting to:', newUrl);
? url.substring(
0,
url.indexOf("/dist-electron") + "/dist-electron".length,
)
: `file://${__dirname}`;
const assetPath = url.split("/assets/")[1];
const newUrl = `${baseDir}/www/assets/${assetPath}`;
callback({ redirectURL: newUrl }); callback({ redirectURL: newUrl });
return; return;
} else {
logger.error('[main.ts] Asset file not found:', assetAbsPath);
}
}
callback({});
} }
callback({}); // No redirect for other URLs
},
); );
if (isDev) { if (isDev) {
@ -157,20 +153,21 @@ function createWindow(): void {
}, },
); );
// Load the index.html // Load the index.html with the correct base URL for assets
mainWindow const baseURL = `file://${path.dirname(indexPath)}/`;
.loadFile(indexPath) logger.log('[main.ts] Loading with base URL:', baseURL);
.then(() => {
try {
await mainWindow.loadURL(`file://${indexPath}`);
logger.log("Successfully loaded index.html"); logger.log("Successfully loaded index.html");
if (isDev) { if (isDev) {
mainWindow.webContents.openDevTools(); mainWindow.webContents.openDevTools();
logger.log("DevTools opened - running in dev mode"); logger.log("DevTools opened - running in dev mode");
} }
}) } catch (err) {
.catch((err) => {
logger.error("Failed to load index.html:", err); logger.error("Failed to load index.html:", err);
logger.error("Attempted path:", indexPath); logger.error("Attempted path:", indexPath);
}); }
// Listen for console messages from the renderer // Listen for console messages from the renderer
mainWindow.webContents.on("console-message", (_event, _level, message) => { mainWindow.webContents.on("console-message", (_event, _level, message) => {

11
temp.har

@ -0,0 +1,11 @@
{
"log": {
"version": "1.2",
"creator": {
"name": "WebInspector",
"version": "537.36"
},
"pages": [],
"entries": []
}
}

6
vite.config.electron.renderer.mts

@ -4,6 +4,7 @@ import path from 'path';
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [vue()],
base: './',
resolve: { resolve: {
alias: { alias: {
'@': path.resolve(__dirname, 'src'), '@': path.resolve(__dirname, 'src'),
@ -12,10 +13,13 @@ export default defineConfig({
build: { build: {
outDir: 'dist-electron/www', outDir: 'dist-electron/www',
emptyOutDir: false, emptyOutDir: false,
assetsDir: 'assets',
rollupOptions: { rollupOptions: {
input: path.resolve(__dirname, 'src/main.electron.ts'), input: path.resolve(__dirname, 'src/main.electron.ts'),
output: { output: {
entryFileNames: 'main.electron.js' entryFileNames: 'main.electron.js',
assetFileNames: 'assets/[name]-[hash][extname]',
chunkFileNames: 'assets/[name]-[hash].js'
} }
}, },
commonjsOptions: { commonjsOptions: {

Loading…
Cancel
Save