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

时间:2018-10-12 05:01:42

标签: angular electron

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

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

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

但是当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'

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

非常感谢

2 个答案:

答案 0 :(得分:0)

  

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

2-service中使用component

export class TestComponent {

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

}

重要提示:在开发人员模式下运行Angular时,出于明显的原因,您总是会收到错误Electron IPC was not loaded。但是,一旦构建了应用程序并使用Electron运行它,一切都将顺利且良好地运行。

经过Angular 8.1.0build --prod的测试和验证。

所有功劳归于original author

答案 1 :(得分:-1)

我会回答,因为我尝试了此解决方案并且它起作用了,很难使其起作用,但是后来我尝试了另一种方法。 我推荐使用ngx-electron,效果很好!!没有问题,而且建立起来很快。

首先必须像以往一样创建main.js。建立您的方法,然后在组件中使用ngx电子。我举了一个例子,使我长期困扰,没有可行的例子

首先进入app.module.ts

import { NgxElectronModule } from 'ngx-electron';

imports: [NgxElectronModule,
  FormsModule ,
  HttpClientModule ,
  BrowserModule,

  ]

然后在您的模块中

在我的情况下,我需要执行静音打印

export class PrincipalComponent implements OnInit {
  @ViewChild('myDiv', {static: false}) myDiv: ElementRef; // reference of view i want to print

   


    constructor(
                      private authenticationService: AuthenticationService,            
                      private _electronService: ElectronService) {}
        generarPdf(){
     
      this.documento ='';
      this.imprimir = true;
      this.horario = formatDate(new Date(), 'dd/MM/yyyy hh:mm', 'en');
    
      this._electronService.ipcRenderer.send('print-to-pdf',  this.myDiv.nativeElement.innerHTML);
      this._electronService.ipcRenderer.on('wrote-pdf', function(event, path){
        this.documento ='';
        console.log('respueta recibida '+ path);
      });
    
      setTimeout(() => 
    {
        this.imprimir =  false;
    },
    3000);
    
    }
       

和main.js

 ipc.on('print-to-pdf',function(event, data){
  console.log('ingreso a imprimiendo');

  win.webContents.printToPDF(pdfSettings()).then(data => {
    const pdfPath = path.join(os.tmpdir(),'./generated_pdf.pdf' );

    win.webContents.print({silent: true}, (success, errorType) => {
      if (!success){
        console.log(errorType)
      } else{
        console.log('print success');
      } 
    })

    fs.writeFile(pdfPath, data, (error) => {
      if (error) throw error
      console.log(`Wrote PDF successfully to ${pdfPath}`)
    })
  }).catch(error => {
    console.log(`Failed to write PDF to ${pdfPath}: `, error)
  }) 

function pdfSettings() {
  var option = {
      landscape: false,
      marginsType: 0,
      printBackground: false,
      printSelectionOnly: false,
      
  };
return option;
}