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

3
  • Possible duplicate of How to include and use node modules in your Ionic / AngularJs app? Commented Apr 15, 2017 at 19:25
  • I think you can use import instead of require have you tried ? Commented Apr 15, 2017 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 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 Commented Apr 17, 2017 at 13:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.