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

问题描述 投票:5回答:1

目前,我正在尝试在也使用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');

之前我遇到了fs.existSsync错误,试图要求别的东西。我通过使用以下tsconfig.app.json修复了它:

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

据我所知,需要远程需求来加载通常只在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);
  }
}

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

node.js angular typescript electron require
1个回答
0
投票

Since Electron v1.6.10,Electron附带TypeScript定义。

要通过TypeScript使用remote,可以使用以下import语句:

import {remote} from 'electron'; 
© www.soinside.com 2019 - 2024. All rights reserved.