Browse Source

debug(electron): app index loads but problem with preload script

pull/134/head
Matthew Raymer 1 week ago
parent
commit
26df0fb671
  1. 2
      package.json
  2. 175
      scripts/build-electron.js
  3. 21
      vite.config.renderer.mts

2
package.json

@ -22,7 +22,7 @@
"check:ios-device": "xcrun xctrace list devices 2>&1 | grep -w 'Booted' || (echo 'No iOS simulator running' && exit 1)", "check:ios-device": "xcrun xctrace list devices 2>&1 | grep -w 'Booted' || (echo 'No iOS simulator running' && exit 1)",
"clean:electron": "rimraf dist-electron", "clean:electron": "rimraf dist-electron",
"build:pywebview": "vite build --config vite.config.pywebview.mts", "build:pywebview": "vite build --config vite.config.pywebview.mts",
"build:electron": "npm run clean:electron && tsc -p tsconfig.electron.json && vite build --config vite.config.electron.mts && node scripts/build-electron.js", "build:electron": "npm run clean:electron && npm run build:web && tsc -p tsconfig.electron.json && vite build --config vite.config.electron.mts && node scripts/build-electron.js",
"build:capacitor": "vite build --mode capacitor --config vite.config.capacitor.mts", "build:capacitor": "vite build --mode capacitor --config vite.config.capacitor.mts",
"build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts", "build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts",
"electron:dev": "npm run build && electron .", "electron:dev": "npm run build && electron .",

175
scripts/build-electron.js

@ -1,165 +1,50 @@
const fs = require('fs'); const fs = require("fs");
const path = require('path'); const fse = require("fs-extra");
const path = require("path");
console.log('Starting electron build process...'); console.log("Starting Electron build finalization...");
// Define paths // Define paths
const electronDistPath = path.join(__dirname, '..', 'dist-electron'); const distPath = path.join(__dirname, "..", "dist");
const wwwPath = path.join(electronDistPath, 'www'); const electronDistPath = path.join(__dirname, "..", "dist-electron");
const wwwPath = path.join(electronDistPath, "www");
const builtIndexPath = path.join(distPath, "index.html");
const finalIndexPath = path.join(wwwPath, "index.html");
// Create www directory if it doesn't exist // Ensure target directory exists
if (!fs.existsSync(wwwPath)) { if (!fs.existsSync(wwwPath)) {
fs.mkdirSync(wwwPath, { recursive: true }); fs.mkdirSync(wwwPath, { recursive: true });
} }
// Create a platform-specific index.html for Electron
const initialIndexContent = `<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0,viewport-fit=cover">
<link rel="icon" href="/favicon.ico">
<title>TimeSafari</title>
</head>
<body>
<noscript>
<strong>We're sorry but TimeSafari doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<script type="module">
// Force electron platform
window.process = { env: { VITE_PLATFORM: 'electron' } };
import('./src/main.electron.ts');
</script>
</body>
</html>`;
// Write the Electron-specific index.html
fs.writeFileSync(path.join(wwwPath, 'index.html'), initialIndexContent);
// Copy only necessary assets from web build
const webDistPath = path.join(__dirname, '..', 'dist');
if (fs.existsSync(webDistPath)) {
// Copy assets directory // Copy assets directory
const assetsSrc = path.join(webDistPath, 'assets'); const assetsSrc = path.join(distPath, "assets");
const assetsDest = path.join(wwwPath, 'assets'); const assetsDest = path.join(wwwPath, "assets");
if (fs.existsSync(assetsSrc)) { if (fs.existsSync(assetsSrc)) {
fs.cpSync(assetsSrc, assetsDest, { recursive: true }); fse.copySync(assetsSrc, assetsDest, { overwrite: true });
} }
// Copy favicon // Copy favicon.ico
const faviconSrc = path.join(webDistPath, 'favicon.ico'); const faviconSrc = path.join(distPath, "favicon.ico");
if (fs.existsSync(faviconSrc)) { if (fs.existsSync(faviconSrc)) {
fs.copyFileSync(faviconSrc, path.join(wwwPath, 'favicon.ico')); fs.copyFileSync(faviconSrc, path.join(wwwPath, "favicon.ico"));
}
} }
// Remove service worker files // Copy manifest.webmanifest
const swFilesToRemove = [ const manifestSrc = path.join(distPath, "manifest.webmanifest");
'sw.js', if (fs.existsSync(manifestSrc)) {
'sw.js.map', fs.copyFileSync(manifestSrc, path.join(wwwPath, "manifest.webmanifest"));
'workbox-*.js',
'workbox-*.js.map',
'registerSW.js',
'manifest.webmanifest',
'**/workbox-*.js',
'**/workbox-*.js.map',
'**/sw.js',
'**/sw.js.map',
'**/registerSW.js',
'**/manifest.webmanifest'
];
console.log('Removing service worker files...');
swFilesToRemove.forEach(pattern => {
const files = fs.readdirSync(wwwPath).filter(file =>
file.match(new RegExp(pattern.replace(/\*/g, '.*')))
);
files.forEach(file => {
const filePath = path.join(wwwPath, file);
console.log(`Removing ${filePath}`);
try {
fs.unlinkSync(filePath);
} catch (err) {
console.warn(`Could not remove ${filePath}:`, err.message);
} }
});
});
// Also check and remove from assets directory // Load and modify index.html from Vite output
const assetsPath = path.join(wwwPath, 'assets'); let indexContent = fs.readFileSync(builtIndexPath, "utf-8");
if (fs.existsSync(assetsPath)) {
swFilesToRemove.forEach(pattern => {
const files = fs.readdirSync(assetsPath).filter(file =>
file.match(new RegExp(pattern.replace(/\*/g, '.*')))
);
files.forEach(file => {
const filePath = path.join(assetsPath, file);
console.log(`Removing ${filePath}`);
try {
fs.unlinkSync(filePath);
} catch (err) {
console.warn(`Could not remove ${filePath}:`, err.message);
}
});
});
}
// Modify index.html to remove service worker registration
const indexPath = path.join(wwwPath, 'index.html');
if (fs.existsSync(indexPath)) {
console.log('Modifying index.html to remove service worker registration...');
let indexContent = fs.readFileSync(indexPath, 'utf8');
// Remove service worker registration script // Inject the window.process shim after the first <script> block
indexContent = indexContent indexContent = indexContent.replace(
.replace(/<script[^>]*id="vite-plugin-pwa:register-sw"[^>]*><\/script>/g, '') /<script[^>]*type="module"[^>]*>/,
.replace(/<script[^>]*registerServiceWorker[^>]*><\/script>/g, '') match => `${match}\n window.process = { env: { VITE_PLATFORM: 'electron' } };`
.replace(/<link[^>]*rel="manifest"[^>]*>/g, '') );
.replace(/<link[^>]*rel="serviceworker"[^>]*>/g, '')
.replace(/navigator\.serviceWorker\.register\([^)]*\)/g, '')
.replace(/if\s*\(\s*['"]serviceWorker['"]\s*in\s*navigator\s*\)\s*{[^}]*}/g, '');
fs.writeFileSync(indexPath, indexContent);
console.log('Successfully modified index.html');
}
// Fix asset paths
console.log('Fixing asset paths in index.html...');
let modifiedIndexContent = fs.readFileSync(indexPath, 'utf8');
modifiedIndexContent = modifiedIndexContent
.replace(/\/assets\//g, './assets/')
.replace(/href="\//g, 'href="./')
.replace(/src="\//g, 'src="./');
fs.writeFileSync(indexPath, modifiedIndexContent);
// Verify no service worker references remain
const finalContent = fs.readFileSync(indexPath, 'utf8');
if (finalContent.includes('serviceWorker') || finalContent.includes('workbox')) {
console.warn('Warning: Service worker references may still exist in index.html');
}
// Check for remaining /assets/ paths
console.log('After path fixing, checking for remaining /assets/ paths:', finalContent.includes('/assets/'));
console.log('Sample of fixed content:', finalContent.substring(0, 500));
console.log('Copied and fixed web files in:', wwwPath);
// Copy main process files
console.log('Copying main process files...');
// Copy the main process file instead of creating a template
const mainSrcPath = path.join(__dirname, '..', 'dist-electron', 'main.js');
const mainDestPath = path.join(electronDistPath, 'main.js');
if (fs.existsSync(mainSrcPath)) { // Write the modified index.html to dist-electron/www
fs.copyFileSync(mainSrcPath, mainDestPath); fs.writeFileSync(finalIndexPath, indexContent);
console.log('Copied main process file successfully');
} else {
console.error('Main process file not found at:', mainSrcPath);
process.exit(1);
}
console.log('Electron build process completed successfully'); console.log("Electron index.html copied and patched for Electron context.");

21
vite.config.renderer.mts

@ -0,0 +1,21 @@
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
export default defineConfig({
root: path.resolve(__dirname, '.'),
base: './',
build: {
outDir: path.resolve(__dirname, 'dist-electron/www'),
emptyOutDir: false,
rollupOptions: {
input: path.resolve(__dirname, 'dist/www/index.html'),
},
},
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
});
Loading…
Cancel
Save