jichoup / electron-typescript-ipc Goto Github PK
View Code? Open in Web Editor NEWLibrary for type-safe use of contextBridge in Electron
License: MIT License
Library for type-safe use of contextBridge in Electron
License: MIT License
Following the readme I get
Compiled with problems:X
ERROR in src/app/components/LogInButton.tsx:4:8
TS2551: Property 'myApi' does not exist on type 'Window & typeof globalThis'. Did you mean 'myAPI'?
2 | import {Button} from "react-bootstrap";
3 |
> 4 | window.myApi.invoke.getDataFromStore('someKey').then(console.log);
| ^^^^^
5 | window.myApi.on.showAlert((_event: any, text: any) => {
6 | alert(text);
7 | });
ERROR in src/app/components/LogInButton.tsx:5:8
TS2551: Property 'myApi' does not exist on type 'Window & typeof globalThis'. Did you mean 'myAPI'?
3 |
4 | window.myApi.invoke.getDataFromStore('someKey').then(console.log);
> 5 | window.myApi.on.showAlert((_event: any, text: any) => {
| ^^^^^
6 | alert(text);
7 | });
8 | type Props = {};
my src/index.ts file:
import { app, BrowserWindow } from 'electron';
import {ipcMain} from "electron-typescript-ipc";
import {Api} from "./electron/api";
// This allows TypeScript to pick up the magic constant that's auto-generated by Forge's Webpack
// plugin that tells the Electron app where to look for the Webpack-bundled app code (depending on
// whether you're running in development or production).
declare const MAIN_WINDOW_WEBPACK_ENTRY: string;
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
app.quit();
}
const createWindow = (): void => {
// Create the browser window.
const width = 992;
const minWidth = 768;
const mainWindow = new BrowserWindow({
width,
minWidth,
height: width*2/3,
minHeight: minWidth*2/3,
webPreferences:{
nodeIntegration: false,
contextIsolation: true,
preload: './electron/preload.ts'
}
});
mainWindow.on('ready-to-show', () => {
ipcMain.removeHandler<Api>('getDataFromStore'); // This is essential in case you are called multiple times.
ipcMain.handle<Api>('getDataFromStore', async (_event, key) => {
return `${key}:foo`;
});
})
// and load the index.html of the app.
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
I can install the package from npm registry regardless of what package manager I use
$ npm i electron-typescript-ipc
npm ERR! code 1
npm ERR! path /Users/golergka/Projects/project-name/node_modules/electron-typescript-ipc
npm ERR! command failed
npm ERR! command sh -c npx only-allow pnpm
npm ERR! ╔═════════════════════════════════════════════════════════════╗
npm ERR! ║ ║
npm ERR! ║ Use "pnpm install" for installation in this project. ║
npm ERR! ║ ║
npm ERR! ║ If you don't have pnpm, install it via "npm i -g pnpm". ║
npm ERR! ║ For more details, go to https://pnpm.js.org/ ║
npm ERR! ║ ║
npm ERR! ╚═════════════════════════════════════════════════════════════╝
Looks like I can only use this package with a project that uses pnpm.
If I add multiple invoke APIs that have different return values then I get the following typescript error:
Type 'Promise<string | void>' is not assignable to type 'Promise<void>'.
Here is a reproducible example:
import './style.css';
import { GetApiType, ipcRenderer } from 'electron-typescript-ipc';
export type Api = GetApiType<
{
getDataFromStore: (str: string) => Promise<string>;
openUrlInBrowser: (str: string) => Promise<void>;
},
{
showAlert: (text: string, num: number) => Promise<void>;
}
>;
declare global {
interface Window {
myAPI: Api;
}
}
const api: Api = {
invoke: {
getDataFromStore: async (key: string) => {
return await ipcRenderer.invoke<Api>('getDataFromStore', key);
},
openUrlInBrowser: async (key: string) => {
return await ipcRenderer.invoke<Api>('openUrlInBrowser', key);
},
},
on: {
showAlert: (listener) => {
ipcRenderer.on<Api>('showAlert', listener);
},
},
};
And here is a codesandbox link (ignore the runtime error because obviously this isn't in an electron environment): https://codesandbox.io/s/practical-river-u5njd?file=/src/index.ts
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.