@ electron-toolkit/ typed- ipc
类型安全电能 IPC, TypeScript中的最佳做法.
主要过程和渲染器过程都有类型检查和智能感. 既可检查又能感知收听器参数,处理器参数和返回值类型,您不会错过任何修改.
它提供了良好的发展经验。 限制IPC注册主要过程和调用渲染器过程,并避免低级出错. 同时,它保持了IPC的原始写作方法,更有利于阅读和理解,而不是过度封装了Electorn's IPC.
使用量
安装
npm i @electron-toolkit/preload @electron-toolkit/typed-ipc
开始
-
使用 @electron-toolkit/ 预装 以曝光电子API.
您可以在指定的预装脚本中披露 :
import { contextBridge } from 'electron' import { electronAPI } from '@electron-toolkit/preload' if (process.contextIsolated) { try { contextBridge.exposeInMainWorld('electron', electronAPI) } catch (error) { console.error(error) } } else { window.electron = electronAPI }或者说
import { exposeElectronAPI } from '@electron-toolkit/preload' exposeElectronAPI() -
添加
*.d.ts声明文件以定义 IPC 事件类型限制 。 并记住把它纳入你的tsconfig 以确保它生效.// Main process ipc events type IpcEvents = | { ping: [string] // listener event map } | { 'say-hello': () => string // handler event map } //Renderer ipc events type IpcRendererEvent = { ready: [boolean] } -
在主过程中注册一个收听器或处理器,或者向渲染器发送信息.
import { IpcListener, IpcEmitter } from '@electron-toolkit/typed-ipc/main' const ipc = new IpcListener<IpcEvents>() const emitter = new IpcEmitter<IpcRendererEvent>() ipc.on('ping', (e, arg) => { console.log(arg) emitter.send(e.sender, 'ready', true) }) ipc.handle('say-hello', () => { return 'hello' }) -
从渲染过程向主进程发送信息,或者聆听主进程的信息.
import { IpcListener, IpcEmitter } from '@electron-toolkit/typed-ipc/renderer' const ipc = new IpcListener<IpcRendererEvent>() const emitter = new IpcEmitter<IpcEvents>() ipc.on('ready', (e, arg) => { console.log(arg) }) emitter.send('ping', 'pong') emitter.invoke('say-hello').then((str) => { console.log(str) })
许可证
麻省理工学院 亚历克斯.wei