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 1 week ago
parent
commit
1c998a777f
  1. 2
      .gitignore
  2. 89
      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
icons
*.log
android/app/src/main/res/

89
src/electron/main.ts

@ -19,7 +19,7 @@ const logger = {
// Check if running in dev mode
const isDev = process.argv.includes("--inspect");
function createWindow(): void {
async function createWindow(): Promise<void> {
// Add before createWindow function
const preloadPath = app.isPackaged
? path.join(app.getAppPath(), "dist-electron", "preload.js")
@ -62,40 +62,36 @@ function createWindow(): void {
// Always open DevTools for now
mainWindow.webContents.openDevTools();
// Intercept requests to fix asset paths
// Intercept requests to robustly fix asset paths for Electron
mainWindow.webContents.session.webRequest.onBeforeRequest(
{
urls: [
"file://*/*/assets/*",
"file://*/assets/*",
"file:///assets/*", // Catch absolute paths
"<all_urls>", // Catch all URLs as a fallback
],
},
{ urls: ["*://*/*"] },
(details, callback) => {
let url = details.url;
// Handle paths that don't start with file://
if (!url.startsWith("file://") && url.includes("/assets/")) {
url = `file://${path.join(__dirname, "www", url)}`;
}
// Handle absolute paths starting with /assets/
if (url.includes("/assets/") && !url.includes("/www/assets/")) {
const baseDir = url.includes("dist-electron")
? 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 });
return;
const url = details.url;
logger.log('[main.ts] Intercepted request:', url);
// Match both file:///assets/... and /assets/...
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)
});
if (fs.existsSync(assetAbsPath)) {
const newUrl = `file://${assetAbsPath}`;
logger.log('[main.ts] Redirecting to:', newUrl);
callback({ redirectURL: newUrl });
return;
} else {
logger.error('[main.ts] Asset file not found:', assetAbsPath);
}
}
callback({}); // No redirect for other URLs
},
callback({});
}
);
if (isDev) {
@ -157,20 +153,21 @@ function createWindow(): void {
},
);
// Load the index.html
mainWindow
.loadFile(indexPath)
.then(() => {
logger.log("Successfully loaded index.html");
if (isDev) {
mainWindow.webContents.openDevTools();
logger.log("DevTools opened - running in dev mode");
}
})
.catch((err) => {
logger.error("Failed to load index.html:", err);
logger.error("Attempted path:", indexPath);
});
// Load the index.html with the correct base URL for assets
const baseURL = `file://${path.dirname(indexPath)}/`;
logger.log('[main.ts] Loading with base URL:', baseURL);
try {
await mainWindow.loadURL(`file://${indexPath}`);
logger.log("Successfully loaded index.html");
if (isDev) {
mainWindow.webContents.openDevTools();
logger.log("DevTools opened - running in dev mode");
}
} catch (err) {
logger.error("Failed to load index.html:", err);
logger.error("Attempted path:", indexPath);
}
// Listen for console messages from the renderer
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({
plugins: [vue()],
base: './',
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
@ -12,10 +13,13 @@ export default defineConfig({
build: {
outDir: 'dist-electron/www',
emptyOutDir: false,
assetsDir: 'assets',
rollupOptions: {
input: path.resolve(__dirname, 'src/main.electron.ts'),
output: {
entryFileNames: 'main.electron.js'
entryFileNames: 'main.electron.js',
assetFileNames: 'assets/[name]-[hash][extname]',
chunkFileNames: 'assets/[name]-[hash].js'
}
},
commonjsOptions: {

Loading…
Cancel
Save