【问题标题】:Angular 6 cannot resolve 'fs' and 'path' for using electronAngular 6 无法解析使用电子的“fs”和“路径”
【发布时间】:2019-03-17 06:34:03
【问题描述】:

我想在angular6项目的typescript中使用ipcRenderer,并通过ipcMain与electron app通信。

在 typescript 文件中访问 ipcRenderer:

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

但是当 ng build 为 Angular 项目时,它会出现

的错误
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'

很多帖子都提到 Angular 6 不能再使用“fs”了。但是我需要使用电子和ipcRenderer,有没有办法解决它?

非常感谢

【问题讨论】:

标签: angular electron


【解决方案1】:

从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-component中使用service

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

【讨论】:

  • 请注意,它也可以在开发模式下运行 Angular 时工作。只要确保您有来自localhost 的电子负载,并且您将webPreferences.nodeIntegration 设置为true
【解决方案2】:

我会回答,因为我尝试了这个解决方案并且它有效,但很难让它发挥作用,但后来我尝试了另一种方法。 我推荐使用 ngx-electron,效果很好!!不涉及任何问题,并且可以快速构建。

首先你必须像往常一样创建你的 main.js。构建您的方法,然后在您的组件中使用 ngx electron。我举了一个让我疯狂了很长时间的例子,但没有有效的例子

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-18
    • 2021-06-05
    • 1970-01-01
    • 2018-07-06
    • 2019-04-09
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多