如何在 svelte 文件中使用 electron 方法 - Svelte 3 - 或者还有其他方法吗?

How to use electron methods inside svelte files - Svelte 3 - or is there any other way to do that?

我一直在从事 Svelte 3 + Electron 12.0.5 项目。我正在使用 svelte-spa-router 包进行哈希路由。我的项目结构如下所示:

node_modules/
public/
    build/
        bundle.css
        bundle.js
    index.html
src/
    Components/
        Pages/
            Home.svelte
            Settings.svelte
            ...
        Sidebar.svelte
        Titlebar.svelte
    App.js
    App.svelte
...
index.js // <-- Electron entry point
rollup|svelte|tailwind // <-- config files

由于我使用的是路由器,electron 的 window.loadFile() 无法正常工作;为了解决这个问题,我使用了 sirv-cli along with concurrently。现在我的启动脚本如下所示:

"start": "concurrently \"sirv public --no-clear --port=40072\" \"electron .\""

现在我使用 window.loadURL("https://localhost:40072") 来实现它。 .svelte 文件,在 <script> 标签内,我尝试做 import * as electron from "electron";但这导致了一个错误,说 fs 未定义。所以现在,我在 index.js 中创建了一个快速服务器,并使用 fetch 向服务器发出 POST 请求,并执行我可以使用 [=21] 轻松完成的事情=] 和 ipcRenderer...我不知道我是否做错了什么(nodeIntegration 已设置为 true)。我是 Svelte 的新手,所以有人知道在脚本标签内使用电子方法的任何其他方法吗?

所以,我终于解决了我的问题。我将此作为答案发布,以便其他有相同问题的人可以解决它。首先,我们不需要快递了(如果你愿意也可以用)。启动脚本相同,即

"start": "concurrently \"sirv public --no-clear --port=40072\" \"electron .\""

所以我们将使用 preload 而不是 nodeIntegration。例如让我们考虑一个自定义标题栏的场景!

--- preload.js ---

const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld(
    "api", { // "api" --> rename it to anything you want
         titlebar: action => {
             ipcRenderer.send("titlebar", action);
         }
    }
);

--- index.js ---

const { app, ipcMain } = require("electron");
...
ipcMain.on("titlebar", (event, arg) => {
    if(arg === "destroy") window.destroy();
    else if(arg === "kill") app.quit();
    else if(arg === "minimize") window.minimize();
    else if(arg === "resize") {
       if(window.isMaximized()) window.unmaximize();
       else window.maximize();
    }
})

最后是你的 svelte 文件;考虑 Titlebar.svelte

<button on:click={() => window.api.titlebar("destroy")}>Destroy</button>
<button on:click={() => window.api.titlebar("kill")}>Kill</button>
<button on:click={() => window.api.titlebar("minimize")}>Minimize</button>
<button on:click={() => window.api.titlebar("resize")}>Resize</button>

这实际上是我的 use-case。我希望它有所帮助!不胜感激!