Require node module in angular2 component

本秂侑毒 提交于 2020-06-27 18:18:49

问题


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.

My component.html has something like this

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

And within the component.ts I use the following

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'.


回答1:


I know the question's been asked over two months ago. But, since this is ranking quite high on Google for some keywords. I'll explain how I got it working...

Option 1

In your index.htm file add the following block inside the head element

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

Then you can declar the electron variable inside any Typescript file, for example, a component...

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

Option 2

This option should be a bit cleaner. If you have a src\typings.d.ts file. Then you can simply tell the typescript compiler to register the require global function...

declare var require: any;

And then you can use the require function as you'd normally do



来源:https://stackoverflow.com/questions/43430276/require-node-module-in-angular2-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!