2

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

cpc
  • 608
  • 6
  • 22
  • Possible duplicate of [How to include and use node modules in your Ionic / AngularJs app?](http://stackoverflow.com/questions/32243203/how-to-include-and-use-node-modules-in-your-ionic-angularjs-app) – skiilaa Apr 15 '17 at 19:25
  • I think you can use import instead of require have you tried ? – Babar Hussain Apr 15 '17 at 23:21
  • Tried that. No compilation error, but at runtime I get the error "fs.existsSync is not a function" and in the stacktrace it is referencing __webpack_require__. instead of the normal node require. The new error is described here https://github.com/electron/electron/issues/7300 but the solution to use window.require does not work for me, since using import instead of require now – cpc Apr 17 '17 at 13:00

1 Answers1

6

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

Community
  • 1
  • 1
Leo
  • 14,625
  • 2
  • 37
  • 55
  • Do you know if there are any disadvantages to Option 2? Seems highly suspect that it's not already available, unless there was some reason... – Xavier Aug 18 '17 at 02:06