简体   繁体   中英

Electron Angular2(angular-cli) require internal module failed

I can't require internal module in my renderer process. When i want to require internal node module or even electron, i got an error or undefined or empty object.

for example:

import * as fs from 'fs';
console.log(fs) // empty object

import { spawn } from 'child_process'; // Can't find child_process module

import * as electron from 'electron' // fs.readFileSync is not a function

Here is my code: Electron

import { app, BrowserWindow } from 'electron';
let mainWin = null;
const loadURL = `http://localhost:4200`;
const createWindow = () => {
    mainWin = new BrowserWindow({
        width: 800,
        height: 800
    });
    mainWin.loadURL(loadURL);
    mainWin.on('closed', () => {
        mainWin = null;
    });
}
app.on('ready', createWindow);
app.on('activate', () => {
    if (!mainWin) {
        createWindow();
    }
});

And renderer process Angular code:

import { Component } from '@angular/core';
import { readdirSync } from 'fs';
import { spawn } from 'child_process';
console.log(readdirSync);
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.styl']
})
export class AppComponent {
  constructor() {}
}

What i'm doing wrong ?

You are including server side modules in Angular which is for the browser.

Electron requires NodeJS the browser can't access the filesystem only the server can.

But Electron renders the index.html file using node so you can require electron via the index.html file

An example using parts of Electron in your Angular app.

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Angular App</title>
  <base href="./">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">


</head>
<body>
  <app-root></app-root>


  <script>
    window.electron = require("electron");
    window.ipcRenderer = require("electron").ipcRenderer;
    window.electronRemote = require("electron").remote;
  </script>


</body>
</html>

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