简体   繁体   English

向 IDE 提供使用电子的 remote.require 导入的模块的 typescript 定义

[英]Provide typescript definition of modules imported using electron's remote.require to the IDE

I want to know if it's possible to get typescript typing of a module in the electron main source directory from the renderer source directory when using electron's remote module for IPC.我想知道在使用电子remote模块用于 IPC 时,是否可以从渲染器源目录中的 electron 主源目录中获取模块的 typescript 类型。

My main goal is to be able to get my IDE to give me autocomplete hints on the types of exports of the module when I'm working with the renderer source directory files.我的主要目标是能够让我的 IDE 在我使用渲染器源目录文件时为我提供有关模块导出类型的自动完成提示。 If it matters, I use both IntelliJ and vscode.如果重要的话,我会同时使用 IntelliJ 和 vscode。

For example, suppose the folder structure of a electron-react app is the following:例如,假设一个电子反应应用程序的文件夹结构如下:

/src
|-- index.tsx       // Entry point for building the renderer app
/lib
|-- electron.ts     // main entry point to initialize electron app
|-- api/            // The module that implements the API contract to the front end
    |-- index.ts

Suppose api/index.ts exports one constant that I want to make available from the React app.假设 api/index.ts 导出了一个我想从 React 应用程序中使用的常量。

export const foo = 1;

From the renderer(React) source files, I can access foo as follows:从渲染器(React)源文件中,我可以按如下方式访问foo

const api = window.require("electron").remote.require("./api")
console.log(api.foo);

However, presumably because of require("./api") the IDE cannot help me figure out what is available from that module.但是,大概是因为require("./api") IDE 无法帮助我弄清楚该模块有什么可用的。 It also cannot determine that foo is a number.它也不能确定foo是一个数字。

How can I help the typescript compiler/IDE figure out the type of api?我如何帮助 typescript 编译器/IDE 找出 api 的类型?

Is it even possible to help the typescript compiler figure out that ...remote.require("./api") is actually the api module in /lib/api ?是否有可能帮助 typescript 编译器找出...remote.require("./api")实际上是/lib/api中的 api 模块?

In this case I define success as the compiler telling me that api.bar is undefined and tells me that api.foo is OK.在这种情况下,我将成功定义为编译器告诉我api.bar未定义并告诉我api.foo

Try explicitly telling TypeScript the type of api with an import type :尝试使用导入类型明确告诉 TypeScript api 的类型api

const api: typeof import('./api') = window.require("electron").remote.require("./api");
api.  // IntelliSense should show a suggestion for `foo` here

I believe you'll have to add the explicitly typings for each import you make in this way.我相信您必须为以这种方式进行的每个导入添加显式类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM