I want to use ipcRenderer in the typescript of angular6 project and communicate with electron app through ipcMain.
To access ipcRenderer in typescript file:
this.ipcRenderer = require('electron').ipcRenderer;
this.ipcRenderer.send('data:submit', '1');
But when ng build for angular project, it comes with the error that
ERROR in ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/xxxx/Developer/angular_bootcamp/ipcStudy/node_modules/electron'
ERROR in ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'path' in '/Users/xxxx/Developer/angular_bootcamp/ipcStudy/node_modules/electron'
A lot of post mentioned that angular 6 can't use 'fs' anymore. But i need to use electron and ipcRenderer, is there anyway to solve it?
Thanks a lot
Copying the answer from link given by OP:
1- Create a service
:
import { Injectable } from '@angular/core';
import { IpcRenderer } from 'electron';
@Injectable({
providedIn: 'root'
})
export class IpcService {
private ipc: IpcRenderer | undefined = void 0;
constructor() {
if ((window as any).require) {
try {
this.ipc = (window as any).require('electron').ipcRenderer;
} catch (e) {
throw e;
}
} else {
console.warn('Electron IPC was not loaded');
}
}
public on(channel: string, listener: any): void {
if (!this.ipc) {
return;
}
this.ipc.on(channel, listener);
}
public send(channel: string, ...args): void {
if (!this.ipc) {
return;
}
this.ipc.send(channel, ...args);
}
}
2- Use service
inside component
:
export class TestComponent {
constructor(private readonly ipc: IpcService) {
this.ipc.on('my-event', (e, val) => {
console.log('my-event: ' + val);
});
}
}
Important Note: While running Angular in dev mode, you'd always get the error Electron IPC was not loaded
, for obvious reasons. But once you build the app and run it with Electron, everything will work smooth and fine.
Tested and verified with Angular 8.1.0
and build --prod
.
All credits to original author.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With