Mastering Electron Forge with TypeScript

In the world of desktop application development, Electron has emerged as a powerful framework that allows developers to build cross - platform desktop applications using web technologies such as HTML, CSS, and JavaScript. Electron Forge is a tool that simplifies the process of creating, packaging, and distributing Electron applications. When combined with TypeScript, a typed superset of JavaScript, it becomes even more powerful, enabling developers to write more robust and maintainable code. This blog post aims to provide a comprehensive guide on using Electron Forge with TypeScript, covering fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Fundamental Concepts
  2. Getting Started
  3. Usage Methods
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

Fundamental Concepts

Electron

Electron is an open - source framework developed by GitHub. It allows you to create desktop applications with web technologies. Electron applications have two main types of processes:

  • Main Process: This is the entry point of an Electron application. It is responsible for creating and managing browser windows and handling system events.
  • Renderer Process: Each browser window in an Electron application runs in its own renderer process. It has access to the DOM and can execute JavaScript code just like a web page.

Electron Forge

Electron Forge is a tool that helps in scaffolding, packaging, and distributing Electron applications. It provides a unified interface for different build and packaging tools, making it easier to manage the development lifecycle of an Electron application.

TypeScript

TypeScript is a statically typed superset of JavaScript. It adds optional types to JavaScript, which helps catch errors early in the development process. TypeScript code needs to be transpiled to JavaScript before it can be executed in a browser or an Electron application.

Getting Started

Prerequisites

  • Node.js and npm (Node Package Manager) installed on your system.

Creating a new Electron Forge project with TypeScript

You can create a new Electron Forge project with TypeScript support using the following command:

npm init electron-forge@latest my - electron - app --template=typescript
cd my - electron - app

This command initializes a new Electron Forge project named my - electron - app using the TypeScript template.

Project Structure

After creating the project, you’ll see a directory structure similar to the following:

my - electron - app
├── src
│   ├── main.ts
│   └── renderer.ts
├── package.json
├── tsconfig.json
└── forge.config.ts
  • src/main.ts: This is the entry point of the main process.
  • src/renderer.ts: This is the entry point of the renderer process.
  • package.json: Contains metadata about the project and its dependencies.
  • tsconfig.json: Configuration file for TypeScript.
  • forge.config.ts: Configuration file for Electron Forge.

Usage Methods

Running the Application

To run the Electron application in development mode, use the following command:

npm start

This command starts the application and opens a new window.

Packaging the Application

To package the application for distribution, use the following command:

npm run make

This command creates a distributable version of the application in the out directory.

Example of Main Process Code (main.ts)

import { app, BrowserWindow } from 'electron';
import * as path from 'path';

function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: false
        }
    });

    mainWindow.loadFile('src/index.html');
}

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

    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

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

Example of Renderer Process Code (renderer.ts)

// This file is loaded whenever a page in the app is loaded.
// You can use this file to add functionality to the renderer process.
window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector: string, text: string) => {
        const element = document.getElementById(selector);
        if (element) element.innerText = text;
    };

    for (const dependency of ['chrome', 'node', 'electron']) {
        replaceText(`${dependency}-version`, process.versions[dependency]);
    }
});

Common Practices

Using Preload Scripts

Preload scripts are used to expose specific APIs from the main process to the renderer process in a secure way. You can create a preload.js file in the src directory:

const { contextBridge } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
    // Define functions or data to expose
    sayHello: () => 'Hello from Electron!'
});

And then use it in the renderer process:

const message = window.electronAPI.sayHello();
console.log(message);

Error Handling

In both the main and renderer processes, it’s important to handle errors properly. For example, in the main process:

app.whenReady().then(() => {
    try {
        createWindow();
    } catch (error) {
        console.error('Error creating window:', error);
    }
});

Best Practices

Type Safety

Make use of TypeScript’s type system to catch errors early. For example, when defining functions in the preload script, use types:

contextBridge.exposeInMainWorld('electronAPI', {
    sayHello: (): string => 'Hello from Electron!'
});

Code Organization

Keep your code organized by separating concerns. For example, you can create separate modules for different functionality in the main and renderer processes.

Performance Optimization

  • Minimize the use of global variables in the renderer process to avoid memory leaks.
  • Use lazy loading techniques to load resources only when needed.

Conclusion

Electron Forge with TypeScript provides a powerful and efficient way to develop cross - platform desktop applications. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can build robust and maintainable applications. Whether you are a beginner or an experienced developer, this combination can help you streamline your development process and create high - quality desktop applications.

References