【问题标题】:How to use electron methods inside svelte files - Svelte 3 - or is there any other way to do that?如何在 svelte 文件中使用电子方法 - Svelte 3 - 还是有其他方法可以做到这一点?
【发布时间】:2021-07-16 18:03:02
【问题描述】:

我一直在从事 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-cliconcurrently。现在我的启动脚本如下所示:

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

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

【问题讨论】:

    标签: javascript node.js electron svelte-3


    【解决方案1】:

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

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

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

    这实际上是我的用例。我希望它有帮助!感谢您的建议!

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2018-08-28
      • 2019-01-02
      • 2020-08-03
      • 2018-11-15
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多