Angular6使用electron时,报错Cannot resolve ‘fs‘ ‘path‘

it2025-04-26  9

想使用ipcRenderer给electron主进程发送消息,但是报错

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'

 

代码是这样的

this.ipcRenderer = require('electron').ipcRenderer; this.ipcRenderer.send('data:submit', '1');

查看了好多,解决方法先创建一个服务

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); } }

然后再要使用的地方

export class TestComponent { constructor(private readonly ipc: IpcService) { this.ipc.on('my-event', (e, val) => { console.log('my-event: ' + val); }); } }

 

 

 

 

最新回复(0)