如何将 Electron ipcRenderer 集成到基于 TypeScript 的 Angular 2 应用程序中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36286592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:23:14  来源:igfitidea点击:

How to integrate Electron ipcRenderer into Angular 2 app based on TypeScript?

javascripttypescriptangularipcelectron

提问by Sommereder

I want to use ipcMain/ ipcRendereron my project to communicate from Angular to Electron and back.

我想在我的项目中使用ipcMain/ ipcRenderer来在 Angular 和 Electron 之间进行通信并返回。

The Electron side is pretty clear:

电子方面很清楚:

const
  electron = require('electron'),
  ipcMain = electron.ipcMain,
;

ipcMain.on('asynchronous-message', function(event, arg) {
  console.debug('ipc.async', arg);
  event.sender.send('asynchronous-reply', 'async-pong');
});

ipcMain.on('synchronous-message', function(event, arg) {
  console.debug('ipc.sync', arg);
  event.returnValue = 'sync-pong';
});

But I have no idea how to integrate that Electron module into my Angular 2 app. I use SystemJSas module loader, but I'm a rookie with it.

但我不知道如何将该 Electron 模块集成到我的 Angular 2 应用程序中。我使用SystemJS作为模块加载器,但我是它的新手。

Any help appreciated. Thanks.

任何帮助表示赞赏。谢谢。

--- Mario

--- 马里奥

采纳答案by DenisKolodin

There is conflict, because Electronuse commonjsmodule resolving, but your code already compiled with systemjsrules.

有冲突,因为Electron使用commonjs模块解析,但是您的代码已经使用systemjs规则编译。

Two solutions:

两种解决方案:

Robust way. Register object requirereturned:

健壮的方式require返回的注册对象:

<script>
    System.set('electron', System.newModule(require('electron')));
</script>

This is the best, because renderer/init.jsscript loads that module on start. SystemJS have to take it only, not loads.

这是最好的,因为renderer/init.js脚本在启动时加载该模块。SystemJS 只需要接受它,而不是加载。

Alternative way. Use dirty trick with declaration.

替代方式。使用带有声明的肮脏技巧。

Get electron instance inside index.html:

在里面获取电子实例index.html

<script>
    var electron = require('electron');
</script>

Declare it inside your typescriptfile this way:

typescript这种方式在您的文件中声明它:

declare var electron: any;

Use it with freedom )

自由使用它)

electron.ipcRenderer.send(...)

回答by user3587412

A recent package called ngx-electronmakes this easy. Link to repoand link to article

最近一个名为的包ngx-electron使这变得容易。链接到 repo链接到文章

src/app/app.module.ts

src/app/app.module.ts

import { NgxElectronModule } from 'ngx-electron';
// other imports 
@NgModule({
  imports: [NgxElectronModule],
  ...
})

src/app/your.component.ts

src/app/your.component.ts

import { Component, NgZone } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-your',
  templateUrl: 'your.component.html'
})
export class YourComponent {
    message: string;        

    constructor(private _electronService: ElectronService, private _ngZone: NgZone) { 
        this._electronService.ipcRenderer.on('asynchronous-reply', (event, arg) => {
            this._ngZone.run(() => {
                let reply = `Asynchronous message reply: ${arg}`;
                this.message = reply;
            });
        }
    }

    playPingPong() {
        this._electronService.ipcRenderer.send('asynchronous-message', 'ping');
    }
}

Note: NgZoneis used because this.messageis updated asynchronously outside of Angular's zone. article

注意:NgZone使用是因为this.message在 Angular 区域之外异步更新。文章

回答by basarat

But I have no idea how to integrate that Electron module into my Angular 2 app

但我不知道如何将该 Electron 模块集成到我的 Angular 2 应用程序中

You would have angularhosted within the UI rendering process in electron. The ipcMainis used to communicate to non rendering child processes.

您将angular在 Electron 的 UI 渲染过程中托管。本ipcMain是用来传达给非渲染子进程。

回答by KarlPurk

This should just be a case of requiring the ipcRenderermodule in your main html file (electron will provide this for you):

这应该只是ipcRenderer在您的主 html 文件中需要模块的情况(电子将为您提供):

<script>
  var ipc = require('electron').ipcRenderer;
  var response = ipc.sendSync('getSomething');
  console.log(response); // prints 'something'
</script>

and then setting up a handler in your main js file:

然后在你的主 js 文件中设置一个处理程序:

const ipcMain = require('electron').ipcMain;
ipcMain.on('getSomething', function(event, arg) {
  event.returnValue = 'something';
});

That's all there should be to it.

这就是它的全部内容。

回答by Charles HETIER

My solution:

我的解决方案:

configure a baseUrl in tsconfig.json

在 tsconfig.json 中配置 baseUrl

at the root of the directory pointed by the baseUrl, create a directory "electron". Inside this directory, a file index.ts:

在 baseUrl 指向的目录的根目录下,创建一个目录“electron”。在这个目录中,有一个文件 index.ts:

const electron = (<any>window).require('electron');

export const {BrowserWindowProxy} = electron;
export const {desktopCapturer} = electron;
export const {ipcRenderer} = electron;
export const {remote} = electron;
export const {webFrame} = electron;

(ideally export default [...]require('electron'), but this is not statically analysable...)

(理想情况下导出默认值 [...]require('electron'),但这不是静态可分析的...)

now I can have in my renderer process:

现在我可以在我的渲染器过程中:

import {remote} from 'electron';
console.log(remote);

Hope it makes sense...

希望这是有道理的...

with typings enabled:

启用打字:

///<reference path="../../typings/globals/electron/index.d.ts"/>
const electron = (<any>window).require('electron');

export const BrowserWindowProxy = <Electron.BrowserWindowProxy>electron.BrowserWindowProxy;
export const desktopCapturer = <Electron.DesktopCapturer>electron.desktopCapturer;
export const ipcRenderer = <Electron.IpcRenderer>electron.ipcRenderer;
export const remote = <Electron.Remote>electron.remote;
export const webFrame = <Electron.WebFrame>electron.webFrame;

NB: typings I got is from:

注意:我得到的打字来自:

{
  "globalDependencies": {
    "electron": "registry:dt/electron#1.4.8+20161220141501"
  }
}

回答by quickreplyguest

Component.TS

组件.TS

const ipc = require('electron').ipcRenderer;

@Component({
    selector: 'app-my component',.....
})

....

....

 public testElectronIpc(): void{
        ipc.send('test-alert');
    }

MAIN.JS

主文件

// IPC message listeners
ipc.on('test-alert', function (event, arg) {
    console.log('Test alert received from angular component');
})

config

配置

plugins: [ new webpack.ExternalsPlugin('commonjs', [ 'desktop-capturer', 'electron', 'ipc', 'ipc-renderer', 'native-image', 'remote', 'web-frame', 'clipboard', 'crash-reporter', 'screen', 'shell' ]) ],

插件:[ new webpack.ExternalsPlugin('commonjs', [ 'desktop-capturer', 'electron', 'ipc', 'ipc-renderer', 'native-image', 'remote', 'web-frame', '剪贴板','崩溃报告','屏幕','外壳'])],