How come I am unable to define global electron variables in my HTML when using Typescript?

I am currently working on a personal project using Electron and Typescript. Both my Main.js and Renderer.js files are in Typescript and compiled. My issue is with the "remote" variable in my template (main.html). While it works within the template, I can't access it in my Typescript app. Here's an example:

// Template - main.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8>
    // other meta tags...
 </head>
 <body>
   <div id="mount"></div>
    <script src="../node_modules/react/dist/react.js></script>
    <script src="../node_modules/react-dom/dist/react-dom.js></script>
    <script type="text/javascript>
       window.remote = require('electron').remote;
       console.log(remote); // Works inside this script tag
    <script src="http://localhost:8080/static/main.bundle.js></script>
 </body>
</html>

While it works within the script tag, it doesn't work in my app. This used to work in another project without any issues. My workaround involves importing the "remote" module into each file before using it. However, this only works with separate webpack configs for different targets - 'electron-renderer' for React and 'electron-main' for Electron.

// TitleBar.tsx
import * as React from "react";
import { Component } from "react";

export default class TitleBar extends Component<any, any> {
  public _close(){
    remote.getCurrentWindow().close(); // This doesn't work!
    // Requires separate webpack targets and global variables in template
  }

  public render() {
    return <button onClick={this._close}>Close Window</button>;
   }    
}

Without setting the proper webpack targets, electron modules won't load. With correct targets, the code should function as expected:

// TitleBar.tsx
import * as React from "react";
import { Component } from "react";
import { remote } from "electron";

export default class TitleBar extends Component<any, any> {
  public _close(){
    remote.getCurrentWindow().close(); // This works now!
    // Proper webpack targets and no need for global variables in template
  }

  public render() {
    return <button onClick={this._close}>Close Window</button>;
   }    
} 

I find it inconvenient to import "remote" every time I need it. Why isn't it working as it used to? Is it an issue with Webpack or Typescript? Any help would be appreciated!

Answer №1

To keep a reference of remote on the global object in the main file, you can follow these steps:

window.remote = remote; // Make sure to import remote before this line.

Afterwards, you will be able to access this reference in other TypeScript files without importing it again. Just remember to use window.remote instead of directly calling remote.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing TypeScript in React FlatList

While TypeScript is a powerful tool, sometimes it feels like I'm working more for TypeScript than it's working for me at the moment. I'm currently using a FlatList to display restaurant results in a Carousel. const renderRestaurantRows = ( ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Steps for resolving the problem of the Express error handler not being executed

This question has come up again, and I have searched for solutions but none seem to work. Your assistance in debugging the issue would be greatly appreciated. I have a separate errorHandler set up as middleware. In my error-handler.ts file: import expres ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

The specified React element type is not valid

Currently working on a web application using Typescript, Electron, Webpack, and NodeJS, but encountering issues with the import/export functionality. The error message that I am facing reads: "Warning: React.createElement: type is invalid -- expect ...

Using an existing function with no arguments as a handler in Typescript and React: A Step-by-Step Guide

NOTE: I'm still learning Typescript, so I may be missing something obvious here. Let's consider a basic scenario in React Javascript, using a Material-UI Button: // Closing dialog event handler without needing an 'event' argument const ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

The error message indicates that the 'aboutData' property is not found within the 'never[]' data type

What is the correct method for printing array elements without encountering the error message "Property 'post_title' does not exist on type 'never[]'?" How can interfaces be used to define variables and utilize them in code for both ab ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

Download pictures from swift into typescript with the help of share extensions

Currently, I am working on setting up Share Extensions in my ionic3 application. To begin with, I followed these steps: Firstly, I built the app and then launched it in Xcode. After that, I added a Share Extension by navigating to File -> New -> Ta ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

Learn how to mock asynchronous calls in JavaScript unit testing using Jest

I recently transitioned from Java to TypeScript and am trying to find the equivalent of java junit(Mockito) in TypeScript. In junit, we can define the behavior of dependencies and return responses based on test case demands. Is there a similar way to do t ...

Tips for extracting a specific segment from a URL string

Take a look at the outcome of the console.log below: console.log('subscribe:', event.url); "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true" I need to ...

Verifying completed fields before submitting

I'm in the process of designing a web form for users to complete. I want all fields to be filled out before they can click on the submit button. The submit button will remain disabled until the required fields are completed. However, even after settin ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Substitute the specific class title with the present class

Here is a sample class (supposed to be immutable): class A { normalMethod1(): A{ const instance = this.staticMethod1(); return instance; } static staticMethod1: A(){ return new this(); } } The code above works fine, but how can I re ...

What are the steps to implement cp-react-tree-table in my application?

Recently diving into TypeScript, I decided to explore the demo provided by https://www.npmjs.com/package/cp-react-tree-table in order to incorporate this control into my project. However, I encountered some unexpected information. After conducting a thoro ...

The Angular translation service may encounter issues when used on different routes within the application

I'm currently working on an Angular application that has multi-language support. To better organize my project, I decided to separate the admin routes from the app.module.ts file and place them in a separate file. However, after doing this, I encounte ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...