简体   繁体   English

在 angular2 组件中需要节点模块

[英]Require node module in angular2 component

I can not figure out how to require node modules in my angular2 components - especially in my case on how to open a new electron window within an angular2 component.我无法弄清楚如何在我的 angular2 组件中要求节点模块 - 特别是在我的情况下如何在 angular2 组件中打开一个新的电子窗口。

My component.html has something like this我的 component.html 有这样的东西

<button class="btn btn-success" (click)="buttonLoginClick()">Login</button>

And within the component.ts I use the following在 component.ts 中,我使用以下内容

export class LoginComponent  {
  constructor() {}

  buttonLoginClick(): void {
    alert("just a test");

    const remote = require('electron').remote;
    const BrowserWindow = remote.BrowserWindow;

    var win = new BrowserWindow({ width: 800, height: 600 });
    win.loadURL('./test.html');
  }
}

The error at compiling is saying编译时的错误是说

Cannot find name 'require'.找不到名称“要求”。

I know the question's been asked over two months ago.我知道这个问题是在两个月前提出的。 But, since this is ranking quite high on Google for some keywords.但是,由于某些关键字在 Google 上的排名很高。 I'll explain how I got it working...我会解释我是如何让它工作的......

Option 1选项1

In your index.htm file add the following block inside the head elementindex.htm文件的head元素中添加以下块

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

Then you can declar the electron variable inside any Typescript file, for example, a component...然后你可以在任何 Typescript 文件中声明电子变量,例如,一个组件......

import { Component } from "@angular/core";

declare var electron: any;

@Component({
    ...
})
export class FooComponent {
    bar() {
        var win = new electron.remote.BrowserWindow({ width: 800, height: 600 });
        win.loadURL('https://google.com.au');
    }
}

when you called that function, it'll open an electron window pointing to google当您调用该函数时,它会打开一个指向 google 的电子窗口

Option 2选项 2

This option should be a bit cleaner.这个选项应该更简洁一些。 If you have a src\\typings.d.ts file.如果您有src\\typings.d.ts文件。 Then you can simply tell the typescript compiler to register the require global function...然后你可以简单地告诉打字稿编译器注册require全局函数......

declare var require: any;

And then you can use the require function as you'd normally do然后你可以像往常一样使用require函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM