如何在 Electron 中制作多个 Svelte 窗口?答案
How to make multiple Svelte windows in Electron?如何在 Electron 中制作多个 Svelte 窗口?
对于我的电子应用程序,我想打开另一个 Svelte 窗口(或根据启动变量加载不同的窗口/组件)。
假设我使用this tutorial 设置了一个基本结构,我的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
文件,以便 body 组件发生变化,如下所示:
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;
这适用于主窗口(即,如果我切换 ID,它会在启动时加载正确的组件)但由于它在打开新窗口时不加载任何 Svelte,所以这不起作用。
所以我非常感谢任何关于如何让 Svelte 为新的/不同的 windows/html 文件加载的想法!如果有办法使用 SvelteKit 做到这一点,那就更好了!
提前谢谢你!