What is the best way to implement multiple preload scripts for various Electron windows when utilizing electron forge with the webpack template?

I am utilizing the typescript+webpack template provided by electron forge.

To load a single preload script with webpack, I need to set the constant called MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY in the package.json file. This constant can be configured like this: "preload": { "js": "myPreload.ts" }. The Electron Forge - Webpack Plugin will then resolve this constant based on whether the application is being run in debug or release mode.

While this setup works well for sharing the same preload script among windows, I am struggling to find a way to specify multiple different preload scripts for separate windows.

How can I incorporate multiple different preload.ts scripts (for various windows) using the electron forge webpack plugin?

Answer №1

I have discovered a simple method for adding multiple scripts, although it may not be widely known. The key factor lies in the name field of the configuration as it determines the prefix of the webpack constant. For example, setting

"name": "my_name"
will create a constant named MY_NAME_PRELOAD_WEBPACK_ENTRY.

To add multiple preload scripts, you need to define multiple entry points with corresponding names. Each entry point must include the html and js fields, but placeholders can be used for unnecessary files.

Here is an illustrative example:

  "config": {
    "forge": {
      "plugins": [
        {
          "name": "@electron-forge/plugin-webpack",
          "config": {
            "mainConfig": "./webpack.main.config.js",
            "renderer": {
              "config": "./webpack.renderer.config.js",
              "entryPoints": [
                {
                  "name": "main_window",
                  "html": "./src/main_window/index.html",
                  "js": "./src/main_window/index.js",
                  "preload": {
                    "js": "./src/main_window/preload.js"
                  }
                },
                {
                  "name": "extra_preload_main_window",
                  "html": "./src/empty.html",
                  "js": "./src/empty.js",
                  "preload": {
                    "js": "./src/main_window/preload2.js"
                  }
                },
                {
                  "name": "second_window",
                  "html": "./src/second_window/index.html",
                  "js": "./src/second_window/index.js",
                  "preload": {
                    "js": "./src/second_window/preload.js"
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }

Corresponding constants are then generated, such as:

// Main window renderer path.
declare MAIN_WINDOW_WEBPACK_ENTRY;

// First main window preload script path.
declare MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY;

// Second main window preload script path.
declare EXTRA_PRELOAD_MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY;

// Other window preload and renderer paths.
declare SECOND_WINDOW_WEBPACK_ENTRY;
declare SECOND_WINDOW_PRELOAD_WEBPACK_ENTRY;

In addition, there is also:

declare EXTRA_PRELOAD_MAIN_WINDOW_WEBPACK_ENTRY;

though this points to an empty file within the webpack output.

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

The jade files are not being detected by gulp.watch()

Out of the blue, my gulpfile.js's watch statement for all of my jade files decided to stop functioning. Any idea why this might be? The Jade task is set up as follows: gulp.task('jade', function() { gulp.src('app/*.jade') . ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

What is the best way to swap out the css selector using jQuery?

Looking to switch the height attribute to min-height This is how I usually update the value, but uncertain about changing the attribute $('.mySelector').css('height','650px') <div class="mySelector" style="cursor: -moz-g ...

The Angular Material side navigation module is not being acknowledged

Currently, I am utilizing Angular version 9.1.11 in conjunction with Angular Material version 9.2.4. The issue arises when attempting to import the MaterialSidenavModule, which is required for utilizing components like mat-sidenav-container. Below is a sn ...

How to handle JavaScript exceptions when encountering a null JSON value?

I am receiving data in JSON format using AJAX from an action in Struts 2 for my view. The data consists of a set of information. For example: {"home": "1234", "room": null} When I try to read data.home, I successfully get the value 1234. However, when a ...

My goal is to retrieve the top three highest rated products

// @route GET /api/products/top // @desc Retrieve top-rated products // @access Available to the public router.get( '/best', asyncHandler(async (req, res) => { const bestProducts = await Product.find({}).sort({ rating: -1 }).limi ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Tips and tricks for implementing vuetify tooltips within a list component

Looking for help with my code: <div id='app'> <v-app> <v-list-tile-content> <v-list-tile v-for="(item, index) in items" :key="item.id" > <v-list-tile-action> {{index+1}}. </v-list-tile-action> < ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...

Causes of the error message 'TypeError: res.render is not a function'

I have set up an express application with the following code: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var request = require(&a ...

A RESTful twist on the traditional Ajax request

I've been using this traditional method to retrieve HTML formatted data through Ajax and insert it into the DOM. http://localhost/ajax-controller/mobile-view/resource/1/ $mobile_view = new View('mobile-view'); // utilizing mobile view $mob ...

Building an HTML form to generate an array of objects by collecting form data

Hey there, I'm working on an HTML form in React that utilizes form action and FormData. However, when I extract the formData using my method, it shows a structure like this: https://i.stack.imgur.com/nzgLX.png My goal is to have an array of objects ...

Designing a layout for a chat application that is structured from the bottom up

I'm currently in the process of designing a web application for a chat platform. I have access to an API that provides a list of messages: chatsite.com/api/thread/1/messages/ [ { "id": 2, "sender": { "id": 2, ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Arranging a collection of objects in alphabetical order

My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array. Array cars = [{ id: 1, ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...

Tips for resolving Electron npm audit fix errors?

This particular inquiry stems from a discussion on Why do renderer fs.existsSync, fs.readfileSync (declared in preload.js) return 'undefined'?, where the issue of method '.toString('base64')' failing due to prototype pollution ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...

Relocating JavaScript scripts to an external file on a webpage served by Node.js' Express

When using Express, I have a route that returns an HTML page like so: app.get('/', function(req, res){ return res.sendFile(path.resolve(__dirname + '/views/index.html')); }); This index.html file contains multiple scripts within t ...