node.js - Angular2 内部的 Node 和 Electron 模块

标签 node.js angular typescript electron

我正在使用 Angular2 开发 Electron 应用程序。

在 Electron 的 main.js 中,我引用/加载 NG 应用程序:

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
  win = new BrowserWindow({width: 800, height: 600})

  // load the index.html of the NG app:
  win.loadURL(url.format({
    pathname: path.join(__dirname, '/../../dist/index.html'),
    protocol: 'file:',
    slashes: true
  }))

[...]

这就像一个魅力。但是,我现在想从NG部分内部访问 Node 和 Electron 的模块。

当我尝试导入例如:fs 模块时:

import * as fs from "fs";

它仍然可以编译,但每当我调用 fs.readFile(...) 时,它都会说:

__WEBPACK_IMPORTED_MODULE_2_fs__.readFile is not a function

当我想到这一点时,这不会也不能工作,因为模块不在 node_modules 文件夹内(对吗?)。 我需要做什么才能使它们在 NG 部分内可用?

最佳答案

如果这仍然相关 -

我还不知道有什么“官方”方式可以做到这一点。但有一些解决方案 - 主要是在index.html中需要 Electron/其他模块并访问window['electron'] -

<script>
    window.electron = require('electron');
</script>
<小时/>

或创建访问 Electron 对象的 Angular 服务。

declare const window: ElectronWindow;
export class ChildProcessService {...}

您可以看到此 Here 的实现

  • ElectronWindow 是指您可以创建并向其添加 require() 函数以处理类型的自定义界面。
  • 使用window.require(*some-node-module*)来存储模块

关于node.js - Angular2 内部的 Node 和 Electron 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809086/

相关文章:

javascript - 如何使用参数设置 Express 路线

javascript - angular 4 如何在外部js中调用一个函数

javascript - 当我尝试在 Typescript 中应用过滤器时出错

angular - 为什么没有按需要调用 TypeScript toString 方法

typescript - NextJS 自定义 404 页面未显示

node.js - 按起始字母排序

javascript - 如何解决此 dialogflow 错误 : text input not set?

angular - 根据 .Net Core 构建选择正确的 Angular 环境

typescript - 带有 gulp-sourcemap : output files to same directory 的 gulp-typescript

javascript - Cordova 应用程序的 session ?