ウェブサイト検索

typescript - Electron Angular2(angular-cli) 内部モジュールの読み込みに失敗


レンダラープロセスで内部モジュールを require できません。内部の Node モジュールや Electron を require しようとすると、エラーが出るか、undefined か空のオブジェクトになります。

例えば:

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

こちらが私のコードです: 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();
    }
});

そしてレンダラープロセスのAngularコード:

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() {}
}

私が間違っていることは何ですか?

回答 #1

あなたはブラウザ用のAngularにサーバーサイドモジュールを含めています。

Electron は NodeJS を必要とします。ブラウザはファイルシステムにアクセスできず、アクセスできるのはサーバーだけです。

しかし、Electronはindex.htmlファイルをNodeを使ってレンダリングするので、index.htmlファイルからelectronをrequireできます

AngularアプリでElectronの一部を使用する例。

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