https://github.com/deiucanta/electron-typed-ipc
Typed IPC for Electron
https://github.com/deiucanta/electron-typed-ipc
Last synced: 5 months ago
JSON representation
Typed IPC for Electron
- Host: GitHub
- URL: https://github.com/deiucanta/electron-typed-ipc
- Owner: deiucanta
- License: mit
- Created: 2020-05-18T11:29:01.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2024-01-02T10:26:15.000Z (almost 2 years ago)
- Last Synced: 2024-04-17T05:45:48.571Z (over 1 year ago)
- Language: TypeScript
- Size: 3.26 MB
- Stars: 8
- Watchers: 3
- Forks: 4
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Electron Typed IPC
- no runtime cost (just typescript enhancements)
- keeps the same API as Electron
- separates events from commands to avoid confusions
- events are things that happened (IPC)
- commands are async functions you can invoke (RPC)## Usage
### 1. Install from npm
```
npm i electron-typed-ipc --save
```### 2. Define your events/commands
```ts
type Events = {
configUpdated: (newConfig?: Config, oldConfig?: Config) => void;
};type Commands = {
fetchConfig: () => Config;
updateConfig: (newConfig: Partial) => void;
};
```### 3. Add types to `ipcMain` and `ipcRenderer`
```ts
import { TypedIpcMain, TypedIpcRenderer } from "electron-typed-ipc";const typedIpcMain = ipcMain as TypedIpcMain;
const typesIpcRenderer = ipcRenderer as TypedIpcRenderer;
```### 4. Emit events and invoke commands
```ts
// renderer.js
const config = await typedIpcRenderer.invoke('fetchConfig');// main.js
typedIpcMain.handle('fetchConfig', () => {
return { a: 1, b: 'text' };
});
``````ts
// renderer.js
typedIpcRenderer.on('configUpdated', (_, newConfig, oldConfig) => {
console.log(newConfig, oldConfig);
});// main.ts
webContents
.getAllWebContents()
.forEach((renderer: TypedWebContents) => {
renderer.send('configUpdated', newConfig, oldConfig);
});
```