Electron TypeScript Starter: A Comprehensive Guide

Electron is an open - source framework developed by GitHub that allows developers to build cross - platform desktop applications using web technologies such as HTML, CSS, and JavaScript. TypeScript, on the other hand, is a superset of JavaScript that adds static typing to the language, making code more robust and maintainable. The Electron TypeScript Starter provides a convenient way to start building Electron applications with TypeScript. It comes with pre - configured settings, build scripts, and project structure, enabling developers to focus on the application logic rather than spending time on setup.

Table of Contents

  1. Fundamental Concepts
  2. Installation and Setup
  3. Usage Methods
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

Fundamental Concepts

Electron

Electron has two main types of processes: the main process and renderer processes.

  • Main Process: This is the entry point of an Electron application. It is responsible for creating and managing browser windows and handling system - level events.
  • Renderer Process: Each browser window in an Electron application runs in its own renderer process. These processes are similar to web pages running in a browser and can access the DOM and web APIs.

TypeScript

TypeScript adds static typing to JavaScript. For example, instead of using a variable without a clear type like this in JavaScript:

let num = 10;

In TypeScript, you can explicitly define the type:

let num: number = 10;

This helps catch type - related errors at compile - time rather than at runtime.

Electron TypeScript Starter

The Electron TypeScript Starter combines the power of Electron and TypeScript. It typically includes a build system (like Webpack or Parcel) to compile TypeScript code into JavaScript and a development server for hot - reloading during development.

Installation and Setup

Prerequisites

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

Steps

  1. Clone the Starter Repository You can use an existing Electron TypeScript starter template from GitHub. For example, the electron - typescript - boilerplate:
    git clone https://github.com/alex8088/electron-typescript-boilerplate.git my - electron - app
    cd my - electron - app
    
  2. Install Dependencies
    npm install
    

Usage Methods

Project Structure

The typical project structure of an Electron TypeScript Starter might look like this:

my - electron - app/
├── src/
│   ├── main/
│   │   └── main.ts # Main process code
│   └── renderer/
│       └── renderer.ts # Renderer process code
├── public/
│   └── index.html # HTML file for the renderer process
├── package.json
├── tsconfig.json # TypeScript configuration
└── webpack.config.js # Webpack configuration (if using Webpack)

Writing Code

Main Process (src/main/main.ts)

import { app, BrowserWindow } from 'electron';

let mainWindow: BrowserWindow;

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

    mainWindow.loadFile('public/index.html');

    mainWindow.on('closed', function () {
        mainWindow = null;
    });
}

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();
});

Renderer Process (src/renderer/renderer.ts)

// Access the DOM
const button = document.createElement('button');
button.textContent = 'Click me';
document.body.appendChild(button);

button.addEventListener('click', () => {
    alert('Button clicked!');
});

Building and Running the Application

  • Development Mode

    npm run dev
    

    This will start the development server with hot - reloading.

  • Production Build

    npm run build
    

    This will compile the TypeScript code and create a distributable version of the application.

Common Practices

Error Handling

In both the main and renderer processes, it’s important to handle errors properly. For example, in the main process, you can handle errors when creating the browser window:

function createWindow() {
    try {
        mainWindow = new BrowserWindow({
            width: 800,
            height: 600,
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false
            }
        });
        mainWindow.loadFile('public/index.html');
    } catch (error) {
        console.error('Error creating window:', error);
    }
}

Communication between Processes

Electron provides the ipcMain and ipcRenderer modules for communication between the main and renderer processes.

Main Process

import { app, BrowserWindow, ipcMain } from 'electron';

ipcMain.on('message - from - renderer', (event, arg) => {
    console.log('Received message from renderer:', arg);
    event.sender.send('message - from - main', 'Message received');
});

Renderer Process

import { ipcRenderer } from 'electron';

ipcRenderer.send('message - from - renderer', 'Hello from renderer');

ipcRenderer.on('message - from - main', (event, arg) => {
    console.log('Received message from main:', arg);
});

Best Practices

Security

  • Context Isolation: Enable context isolation in the renderer process to prevent the renderer from directly accessing Node.js APIs. This helps protect against potential security vulnerabilities.
mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js')
    }
});
  • Preload Script: Use a preload script to expose only the necessary APIs to the renderer process.

Code Organization

  • Modularize Code: Break your code into smaller, reusable modules. For example, you can create separate modules for handling different types of events or functionality.
  • Follow Coding Standards: Adopt a consistent coding style (e.g., ESLint with TypeScript rules) to make the codebase more maintainable.

Conclusion

The Electron TypeScript Starter is a powerful tool for building cross - platform desktop applications. By combining the capabilities of Electron and TypeScript, developers can create robust, maintainable, and secure applications. Understanding the fundamental concepts, following the usage methods, and adopting common and best practices will help you make the most out of this technology stack.

References