首页 文章

如何在打字稿中加载电子模块

提问于
浏览
5

我尝试从typescript中的电子获取ipcRenderer模块,将信息从当前组件发送到核心并将信息返回到窗口(电子铬浏览器) . 通过将ts代码转码为ES5,我得到的是“未找到模块”错误 .

const ipc = require('electron') . ipcRenderer;`

Update: 错误在"Module not found"与此之间切换:

ERROR in ./~/electron/index.js Module build failed: Error: ENOENT, open '/.../node_modules/electron/index.js' @ ./app/components/search/search.ts 12:10-29

那是从当前的electron-api . 我也尝试使用typescript中的import语法,但结果是一样的 .

比我尝试在ES5文件中使用electron.ipcRenderer模块,直接在html文件中加载/链接 .

在那里工作 . 为什么?

3 回答

  • 1

    由于浏览器应用程序中的电子依赖性不是真实的,这意味着它不是从node_modules进行webpacked而是在运行时加载,因此require语句导致错误,例如找不到“fs” .

    但是你可以用这个来欺骗打字稿:

    if (typeof window['require'] !== "undefined") { let electron = window['require']("electron"); let ipcRenderer = electron.ipcRenderer; console.log("ipc renderer", ipcRenderer); }

    此外,如果您正在编写一个Web应用程序,只有当它在内部运行时才通过电子增强,这是一种更好的方法,因为您不必在使用通信部件时将电子作为依赖项添加到您的webapp .

  • 4

    比我尝试在ES5文件中使用electron.ipcRenderer模块,直接在html文件中加载/链接 .

    如果它在html中工作但在ts中失败则意味着错误不在 const ipc = require('electron').ipcRenderer; 中 . 导入中的错误非常类似于从html(而不是 require('electron') )加载文件 .

相关问题