Lejdi Prifti

0 %
Lejdi Prifti
Software Engineer
DevOps Engineer
ML Practitioner
  • Residence:
    Albania
  • City:
    Tirana
  • Email:
    info@lejdiprifti.com
Spring
AWS & Cloud
Angular
Team Player
Coordination & Leadership
Time Management
Docker & Kubernetes
ReactJs
JavaScript
Python
  • Java, JavaScript, Python
  • AWS, Kubernetes, Azure
  • Bootstrap, Materialize
  • Css, Sass, Less
  • Blockchain, Ethereum, Solidity
  • React, React Native, Flutter
  • GIT knowledge
  • Machine Learning, Deep Learning
0

No products in the basket.

Converting React app into an Electron desktop application

23. August 2024

Introduction

In this article, we’ll walk through the process of converting our React app into an Electron desktop application, making it compatible with both Ubuntu and Windows platforms. We’re typically used to running React applications on a Node.js server at localhost:3000, but in this case, the app will run as an Electron desktop application, loading files directly from the local directory.

Table of Contents

What is Electron?

Electron is an open-source framework that enables us to build cross-platform desktop applications using web technologies like HTML, CSS, and JavaScript. By combining Chromium and Node.js, Electron allows us to create apps that run on Windows, macOS, and Linux, all from a single codebase.

It’s widely used for developing desktop applications because it leverages familiar web development tools while providing access to native OS features.

Dependency installation

To begin the transformation, we need to install a few dependencies necessary for working with Electron. 

The electron  package includes the core framework that will allow us to build and run our Electron application. It provides the necessary tools to combine Chromium and Node.js, enabling our React app to function as a desktop application. Installing it as a development dependency ensures that it’s only included in the development environment, not in the final production build. 

On the other hand, the electron-packager  package is used to package our Electron application for distribution. It bundles the app and its dependencies into executables for different operating systems (Windows, macOS, Linux). It makes it easier to share our application with users. 

Pay attention! It is not recommended to install these packages globally.

				
					npm install --save-dev electron electron-packager
				
			

Configuring main.js

In the root directory of our React application, we must create the main.js file that serves as the entrypoint of the Electron app. 

We start by importing the necessary modules from Electron, specifically app and BrowserWindow from the electron/main package. The app module controls the application’s lifecycle events. On the other hand, BrowserWindow is responsible for creating and managing application windows.

Afterwards, we define the createWindow function to set up the main application window. Inside this function, it instantiates a new BrowserWindow with specific properties such as width and height and passes a configuration object to the webPreferences option to enable Node.js integration within the renderer process.

				
					const { app, BrowserWindow } = require("electron/main");

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
  });

  const filePath = `build/index.html`;
  !app.isPackaged ? mainWindow.loadURL("http://localhost:3000") : mainWindow.loadFile(filePath);
  mainWindow.on("closed", () => (mainWindow = null));
}

app.whenReady().then(() => {
  createWindow();
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

app.on("activate", () => {
  if (mainWindow === null) {
    createWindow();
  }
});

				
			

Moreover, the function determines the file or URL to load based on whether the application is packaged.

If the application is in development mode (!app.isPackaged), it loads a local development server at http://localhost:3000. Otherwise, it loads an HTML file from the application’s distribution directory (dist/index.html).

The mainWindow.on("closed", ...) event handler ensures that when the window is closed, the mainWindow variable is set to null, allowing the application to clean up resources and properly handle window re-creation.

The app.whenReady() method is called to ensure that the Electron app is fully initialized before creating the window. Once the app is ready, it invokes the createWindow function. The app.on("window-all-closed", ...) event handler listens for all windows being closed. If the platform is not macOS (i.e., not “darwin”), the application quits. This behavior is specific to macOS, where applications typically remain active even after closing all windows.

Finally, the app.on("activate", ...) event handler listens for the application being reactivated, such as when the user clicks the app’s dock icon on macOS. If no window exists (mainWindow === null), it calls the createWindow function again to reopen the main window.

Configuring package.json

A key step in converting a React application into an Electron desktop application is updating the package.json file to specify the new entry point and revise the homepage setting. 

				
					{
  "name": "react-electron-app",
  "version": "0.1.0",
  "private": true,
  "main": "main.js",
  "homepage": "./",
  // ...
}
				
			

Setting the homepage to ./ ensures that index.html will search for files in the local directory, as shown in the code snippet below. This snippet is from the generated index.html in the build directory.

				
					<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <link rel="icon" href="./favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app" />
    <link rel="apple-touch-icon" href="./logo192.png" />
    <link rel="manifest" href="./manifest.json" />
    <title>React App</title>
    <script defer="defer" src="./static/js/main.8f32d6e3.js"></script>
    <link href="./static/css/main.f855e6bc.css" rel="stylesheet">
</head>

<body><noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>

</html>
				
			

To successfully package our React application as an Electron desktop app, it’s essential to update with specific Electron commands the scripts section. These commands simplify the process of packaging our application for different platforms.

For instance, adding "package:linux": "electron-packager . react-electron-app --overwrite" allows us to package the app for Linux, while "package:win": "electron-packager . react-electron-app --platform=win32 --arch=x64 --overwrite" targets Windows with 64-bit architecture.

				
					{
 // ...
"scripts": {
    "package:linux": "electron-packager . react-electron-app --platform=linux --arch=x64 --overwrite",
    "package:win": "electron-packager . react-electron-app --platform=win32 --arch=x64 --overwrite",
    "package:mac": "electron-packager . react-electron-app --platform=darwin --arch=x64 --overwrite",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
 // ...
}
				
			

Additionally, including the command "electron": "electron ." in the scripts section of our package.json file allows us to easily launch our Electron application in development mode. This command tells Electron to start the application using the current directory, providing a quick way to test and debug our app before packaging it for different platforms. 

Running Electron in development mode

Running our Electron desktop application in development mode is crucial for efficient development, faster debugging, and various other reasons.

To achieve this, we need to execute two processes on our machine. First, we must run the React application on localhost:3000

				
					npm run start
				
			

Secondly, we must run the Electron application. As soon as you execute the following command, you must expect a Chromium window to open. 

				
					npm run electron
				
			

Running Electron in production mode

To run the Electron desktop application in production mode, we need to package it for the target platform and distribute it. Since I am using an Ubuntu machine, I will package the application for Linux and execute it. You should build the application according to your target platform, depending on where you plan to run it.

				
					npm run package:linux
				
			

Inside the generated folder react-electron-app-linux-x64 , I see the react-electron-app application (if on Windows, it must be react-electron-app.exe). Clicking on it launches the Electron desktop application.

Electron desktop application

Pay attention! If you’re using BrowserRouting in React, be aware that it might cause issues in a Windows environment. To resolve this, switch to HashRouting instead.

Conclusion

Converting a React application into an Electron desktop application involves several key steps to ensure a smooth transition and effective packaging.

If you encounter difficulties, focus on the base paths and ensure that all files are being loaded correctly. If you need help, contact me.

Checkout blog for more articles on React, Angular and Spring Boot. 

Posted in ReactTags: