【发布时间】:2018-06-21 02:39:25
【问题描述】:
目前,我正在尝试在也使用 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);
}
}
将此服务注入我的组件并调用 electronService.require('opencv4nodejs') 也不起作用。
【问题讨论】:
-
通过阅读此错误
Without window I get "Uncaught TypeError: fs.existsSync is not a function,您似乎正在捆绑您的渲染器端代码? -
我认为渲染器端代码正在被 Electron 捆绑,虽然我在 NodeJS 等方面还很新,所以我真的不确定。
标签: node.js angular typescript electron require