如何使用TypeScript在Electron中使用remote.require()

Scu*_*Kay 5 require node.js typescript electron angular

当前,我正在尝试在也使用TypeScript的Electron / Angular应用程序中使用opencv4nodejs模块。我尝试了几种方法来做到这一点。以下代码块显示了我尝试过的内容以及收到的错误消息。

// This says cv is undefined:
const cv = window.require('electron').opencv4nodejs;
const img = cv.imread('../assets/poop.jpg');

// Same here:
const cv = window.require('electron').remote.opencv4nodejs;
const img = cv.imread('../assets/poop.jpg');

// Uncaught Error: The specified module could not be found. (Though the module does exist at that location)
const cv = window.require('electron').remote.require('opencv4nodejs');
const img = cv.imread('../assets/poop.jpg');

// Without window I get "Uncaught TypeError: fs.existsSync is not a function"
const remote = require('electron').remote;
const cv = remote.opencv4nodejs;
const img = cv.imread('../assets/poop.jpg');
Run Code Online (Sandbox Code Playgroud)

我之前遇到过fs.existSync错误,尝试要求其他操作。我通过使用以下tsconfig.app.json修复了该问题:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": ["node"] // Included this line
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

据我了解,需要远程需求来加载通常仅在node.js服务器上运行的模块。仍然我似乎仍然无法弄清楚如何在我的应用程序中需要该模块。该模块的作者对构建问题和其他问题很有帮助,但他从未将其模块与TypeScript一起使用。

我如何在基于TypeScript / Angular / Electron的应用程序中远程要求一个模块?

[编辑]

我还尝试了以下方法:

import { Injectable } from '@angular/core';

// If you import a module but never use any of the imported values other than as TypeScript types,
// the resulting javascript file will look as if you never imported the module at all.
import { ipcRenderer } from 'electron';
import * as childProcess from 'child_process';

@Injectable()
export class ElectronService {

  ipcRenderer: typeof ipcRenderer;
  childProcess: typeof childProcess;

  constructor() {
    // Conditional imports
    if (this.isElectron()) {
      this.ipcRenderer = window.require('electron').ipcRenderer;
      this.childProcess = window.require('child_process');
    }
  }

  isElectron = () => {
    return window && window.process && window.process.type;
  }

  require = (module: string) => {
    return window.require('electron').remote.require(module);
  }
}
Run Code Online (Sandbox Code Playgroud)

将此服务注入到我的组件中并调用electronService.require('opencv4nodejs')也不起作用。

nde*_*ker 0

从 Electron v1.6.10 开始,Electron 附带了 TypeScript 定义。

为了remote通过 TypeScript 使用,您可以使用以下 import 语句:

import {remote} from 'electron'; 
Run Code Online (Sandbox Code Playgroud)