Angular 6无法解析使用电子的“ fs”和“ path”

rod*_*_la 7 electron angular

我想在angular6项目的打字稿中使用ipcRenderer,并通过ipcMain与电子应用进行通信。

要在打字稿文件中访问ipcRenderer:

this.ipcRenderer = require('electron').ipcRenderer;
this.ipcRenderer.send('data:submit', '1');
Run Code Online (Sandbox Code Playgroud)

但是当ng为有角度的项目构建时,它会带来以下错误:

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'
Run Code Online (Sandbox Code Playgroud)

许多帖子提到角度6不再可以使用'fs'。但是我需要使用electronic和ipcRenderer,有解决方法吗?

非常感谢

Sye*_*aqi 5

从 OP 给出的链接中复制答案:

1-创建一个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);
  }
}
Run Code Online (Sandbox Code Playgroud)

2-service内部使用component

export class TestComponent {

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

}
Run Code Online (Sandbox Code Playgroud)

重要提示:在开发模式下运行 Angular 时Electron IPC was not loaded,由于显而易见的原因,您总是会收到错误消息。但是一旦你构建了应用程序并使用 Electron 运行它,一切都会顺利进行。

Angular 8.1.0和 进行测试和验证build --prod

所有学分均归原作者所有。