gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:40:23 33 4
gpt4 key购买 nike

目前,我正在尝试在同样使用 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.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"
]
}

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

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

[编辑]

我还尝试了以下方法:

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);
}
}

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

最佳答案

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

为了通过 TypeScript 使用远程,您可以使用以下导入语句:

import {remote} from 'electron'; 

关于node.js - 如何使用 TypeScript 在 Electron 中使用 remote.require(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48212619/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com