简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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