Electron & Angular: fs.existsSync 不是函数

Electron & Angular: fs.existsSync is not a function

我用 Angular 创建了一个新的电子项目。我使用 Angular CLI 构建我的应用程序。 现在,我想从 Renderer-Process 到 Main-Process 进行通信,并在 Dev-Tools 中出现错误:

> Uncaught TypeError: fs.existsSync is not a function
    at Object.<anonymous> (vendor.bundle.js:72643)
    at Object.splitPathRe (vendor.bundle.js:72649)
    at __webpack_require__ (inline.bundle.js:53)
    at Object.399 (main.bundle.js:54)
    at __webpack_require__ (inline.bundle.js:53)
    at Object.400 (main.bundle.js:107)
    at __webpack_require__ (inline.bundle.js:53)
    at Object.291 (main.bundle.js:24)
    at __webpack_require__ (inline.bundle.js:53)
    at Object.473 (main.bundle.js:234)
    at __webpack_require__ (inline.bundle.js:53)
    at webpackJsonpCallback (inline.bundle.js:24)
    at main.bundle.js:1

我使用这个项目模板:https://github.com/auth0-blog/angular2-electron 重现此错误的步骤是:

git clone https://github.com/auth0-blog/angular2-electron
npm install

3.Add 下一行 src/app/app.component.ts

const {ipcRenderer} = require('electron');

没有那一行,应用程序运行没有任何问题。 由于电子,我必须以这种方式引用 ipcRenderer ... https://github.com/electron/electron/blob/master/docs/api/ipc-main.md

我不知道我做错了什么,希望你能帮助我。

Webpack 自带 require 会破坏 node.js' require,所以当你 require 一个 Webpack 无法解析的 node.js 核心模块时对于您的文件或依赖项之一,它会抛出。 (您可以在堆栈跟踪中看到它包含 __webpack_require__。这是因为 webpack 将所有 require 重写为 __webpack_require__,以便它使用自己的内部 node.js-esque 系统) . Webpack 是为 web/browsers 构建的,因此它不能很好地与开箱即用的节点一起使用。要绕过它,你可以使用这个:https://github.com/chentsulin/webpack-target-electron-renderer

但我也会考虑使用 webpack,请参阅:

我有一个问题,下面的代码解决了它。希望也能解决你的问题

在你的yourcustom.component.ts

declare const window: any;
declare const ipcRenderer: any;
ipcRenderer = window.require('electron');
// then you can continue what you want to do with ipcRenderer.

您可以像下面这样使用

const { BrowserWindow } = (<any>window).require('electron')

`

declare var window: ElectronWindow;

interface ElectronWindow {
    process: any;
    require: any;
    sudo: any;
}

let _rawRequire;
if (window && window.require) {
    _rawRequire = require;
    require = window.require;
}

/*** import the node module here ***/
import * as childProcess from 'child_process';
import { app, shell, ipcRenderer, OpenDialogOptions } from 'electron'
import { ChildProcess } from "child_process";
// import sudo  from 'sudo-prompt';
import Sudoer from 'electron-sudo';


if (_rawRequire) {
    require = _rawRequire;
}

/***  import the angular module here ***/
import { TS } from "typescript-linq";
import Exception = TS.Exception;
import { Injectable } from '@angular/core';
import { ElectronService } from "ngx-electron";

`