简体   繁体   中英

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.

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. If it matters, I use both IntelliJ and 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.

export const foo = 1;

From the renderer(React) source files, I can access foo as follows:

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. It also cannot determine that foo is a number.

How can I help the typescript compiler/IDE figure out the type of api?

Is it even possible to help the typescript compiler figure out that ...remote.require("./api") is actually the api module in /lib/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.

Try explicitly telling TypeScript the type of api with an import type :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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