alex8088 / electron-vite-boilerplate

Comprehensive and security Electron template (TypeScript + Vue3 + Vite).
https://electron-vite.org
141 stars 25 forks source link

ipcRenderer and ipcMain examples #6

Closed soupman99 closed 1 year ago

soupman99 commented 1 year ago

I looked a bit but didn't see any examples of how to use messaging between process in a svelte application.

Can you give some hints?

when I try import { ipcRenderer } from "electron"; in a TS render process file I get the error:

browser-external:path:9 Module "path" has been externalized for browser compatibility. Cannot access "path.join" in client code. get @ browser-external:path:9 index.js:4 Uncaught ReferenceError: __dirname is not defined at node_modules/electron/index.js (index.js:4:28) at __require2 (chunk-7FP5O474.js?v=b49c6588:10:50) at index.js:21:34

soupman99 commented 1 year ago

Nevermind, I kept trying and got it working. Thanks for the great project starter! Below is what I did to set it up incase someone else gets stuck.

Add this to 'src/render/main.ts'

import { ElectronAPI } from '@electron-toolkit/preload' declare global { interface Window { electron: ElectronAPI } }

Added this to '/src/main/main.ts' ipcMain.on('asynchronous-reply', function(event, arg) { console.log(arg) // prints "pong" event.reply('asynchronous-reply', 'pong') }) // you should see this response in the main console (where you ran npm run dev)

Added this to any of my render view project files. You might be able to just add it to App.svelte window.electron.ipcRenderer.on('asynchronous-reply', (_event, arg) => { console.log(async reply, arg) // prints "pong" in the DevTools console of the electron window. })