javascript - 如何在 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-cli和concurrent。现在我的启动脚本如下所示:
"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 有点陌生,所以有人知道在脚本标签中使用电子方法的任何其他方式吗?
解决方案
所以,我终于解决了我的问题。我将其发布为答案,以便其他有相同问题的人可以解决它。首先,我们不再需要 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>
这实际上是我的用例。我希望它有帮助!建议表示赞赏!
推荐阅读
- python - 在 CentOS 上安装 Networkit 时出错
- angular - 在 Angular(v2 及更高版本)反应形式表单数组中获取无效控件
- python - ValueError:“图像”必须具有 3 或 4 个维度
- graphql - Nextjs - 内容丰富 - 标签 - 动态页面
- nuxt.js - Nuxt fetch 钩子:为什么在服务器和客户端都触发?
- python - 我在 Linux/Ubuntu 系统上的 Virtualenv 中使用 Python3,pyaudio 已安装,但无法在 Jupyter Notebook 中导入
- php - Xdebug 在 Composer 插件中不可用
- c# - 无法让 MySQL Connector/NET 在 Ubuntu 上工作
- c# - CefSharp Winform MDI
- java - rust 和 JNI crate - 将 java 对象转换为字节数组并返回它们并返回空字段