首页 > 解决方案 > 如何在 svelte 文件中使用电子方法 - Svelte 3 - 还是有其他方法可以做到这一点?

问题描述

我一直在从事 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

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

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

现在我曾经window.loadURL("https://localhost:40072")得到这个工作。.svelte文件,在<script>标签内,我试着做import * as electron from "electron";但这导致错误说fs未定义。所以现在,我在内部创建了一个快速服务器,index.js并使用 usingfetch向服务器发出POST请求并执行我可以轻松完成的工作ipcMain......ipcRenderer我不知道我是否做错了什么(nodeIntegration 是已经设置为真)。我对 Svelte 有点陌生,所以有人知道在脚本标签中使用电子方法的任何其他方式吗?

标签: javascriptnode.jselectronsvelte-3

解决方案


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

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

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

--- 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();
    }
})

最后是你的苗条文件;考虑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>

这实际上是我的用例。我希望它有帮助!建议表示赞赏!


推荐阅读