对于我的电子应用程序,我想打开另一个Svelte窗口(或者根据启动变量加载不同的窗口/组件)。
假设我使用本教程来设置一个基本结构,我的App.svelte如下所示:
<script>
const openLauncher = () => {
window.api.openWindow("launcher");
};
</script>
<button on:click={openLauncher}>Open Launcher</button>如您所见,我添加了一个IPC函数来打开一个新窗口。对应的index.js
const { app, BrowserWindow, ipcMain } = require("electron");
const { join } = require("path");
app.on("ready", () => {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: join(__dirname, "./preload.js"),
}
});
mainWindow.loadFile(join(__dirname, "../public/index.html"));
});
ipcMain.on("openLauncher", (event, args) => {
const launcher = new BrowserWindow({
webPreferences: {
preload: join(__dirname, "./preload.js"),
}
});
launcher.loadFile(join(__dirname, "../public/launcher.html"));
});preload.js
const { contextBridge, ipcRenderer } = require("electron");
const API = {
openWindow: (obj) => ipcRenderer.send("openLauncher", obj),
}
contextBridge.exposeInMainWorld("api", API);这确实可以用launcher.html打开一个新窗口,但是我不知道如何让Svelte组件在这个新文件中工作。
我的一个想法是修改main.js文件,使主体组件发生变化,如下所示:
import App from './App.svelte';
import LauncherApp from './LauncherApp.svelte';
const bodyID = document.getElementsByTagName('body')[0].id;
const app = {};
if (bodyID == "index") {
app = new App({
target: document.body,
});
}
else if (bodyID == "launcher") {
app = new LauncherApp({
target: document.body,
});
}
export default app;这适用于主窗口(即,如果我切换I,它在启动时加载正确的组件),但由于它在打开新窗口时没有加载任何Svelte,因此无法工作。
因此,我非常感谢任何关于如何让Svelte加载新的/不同的windows/html-文件的想法!如果有办法用SvelteKit做到这一点,那就更好了!
提前谢谢你!
发布于 2022-11-21 21:55:41
由于这篇文章帮助我创建了很多使用Svelte和电子的独立窗口,所以我不得不在隐藏堆栈溢出数年之后创建我的帐户。我想我已经解决了你的问题没有“黑客”的解决办法。
我让它在没有原始App.svelte中的#IF语句的情况下工作。我就是这样做的:
我在src地图中的main.js (渲染器方面)如下:
import App from './App.svelte';
import Window2 from './Window2.svelte';
let bodyID = document.getElementsByTagName('body')[0].id;
let app;
if (bodyID == "index"){
app = new App({
target: document.body,
});
}
else if (bodyID == "window2"){
app = new Window2({
target: document.body,
});
}
export default app;然而,我认为真正的魔力发生在我的index.html和Window2.html中。我是用Tylerlaceby提供的优秀YouTube视频制作的。
基本上,主文件夹中的index.js (所以电子主js)用以下行打开窗口:
const main_window = new BrowserWindow({//Your settings
});
main_window.loadFile(join(__dirname, "../public/index.html"));
main_window.on("ready-to-show", main_window.show);公用文件夹中的index.html包含以下标题:
<title>Main Window</title>
<link rel='icon' type='image/png' href='./favicon.ico'>
<link rel='stylesheet' href='global.css'>
<link rel='stylesheet' href='build/bundle.css'>
<script defer src='build/bundle.js'></script>主体是空的,但是有我在main.js渲染器脚本中使用的id。
我相信index.html中的标题在构建电子应用程序之后加载构建文件夹,包含所有转换后的Svelte文件。
Window2.html是相同的。辅助窗口以与主窗口相同的方式从电子端的main.js加载第二个代码块,但引用了Window2.html。with包含一个ID为Window2的主体。
如果以上不是解决方案,也可能是因为我使用let而不是const。一旦一个变量被赋值给const,它就不能被更改--这可能解释为什么它第一次工作,而不是第二次。
我很抱歉,如果我没有得到所有的格式和引用以前的and器正确。我仍然习惯于学习Stackoverflow,但是我渴望分享我是如何让它为我工作的。
https://stackoverflow.com/questions/71079628
复制相似问题