Last Updated: 

Electron TypeScript Template: 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 typed superset of JavaScript that compiles to plain JavaScript. Combining Electron with TypeScript provides a more robust and maintainable development experience, especially for larger projects. An Electron TypeScript template is a pre-configured starting point that helps developers quickly set up an Electron project with TypeScript support.

Table of Contents#

  1. Fundamental Concepts
  2. Setting up an Electron TypeScript Template
  3. Usage Methods
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

1. Fundamental Concepts#

Electron#

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

  • Main Process: It is responsible for creating and managing browser windows. It has full access to Node.js APIs, which allows it to interact with the operating system at a low level.
  • Renderer Process: Each browser window in Electron runs a renderer process. It is similar to a traditional web page, where JavaScript can be used to manipulate the DOM. However, it also has access to some Node.js APIs, enabling it to perform tasks like file I/O.

TypeScript#

TypeScript adds static typing to JavaScript. This means that you can define the types of variables, function parameters, and return values. For example:

// A simple function with typed parameters and return value
function add(a: number, b: number): number {
    return a + b;
}

The type system helps catch errors early in the development process and makes the code more self-documenting.

Electron TypeScript Template#

An Electron TypeScript template provides a basic project structure, configuration files, and build scripts to get you started with an Electron project using TypeScript. It typically includes a tsconfig.json file for TypeScript configuration, a package.json file for project metadata and dependencies, and a build script to compile TypeScript code.

2. Setting up an Electron TypeScript Template#

Using a Boilerplate#

One of the easiest ways to set up an Electron TypeScript project is to use a boilerplate like electron - forge with TypeScript support.

Step 1: Install Electron Forge#

npm install -g electron-forge

Step 2: Create a new Electron project with TypeScript#

electron-forge init my-electron-ts-app --template=typescript
cd my-electron-ts-app

Manual Setup#

If you prefer a manual setup, here are the steps:

Step 1: Initialize a new Node.js project#

mkdir my-electron-ts-app
cd my-electron-ts-app
npm init -y

Step 2: Install Electron and TypeScript#

npm install electron typescript --save-dev

Step 3: Create a tsconfig.json file#

{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules"]
}

Step 4: Create the project structure#

Create a src directory and add a main.ts file for the main process and a renderer.ts file for the renderer process.

Step 5: Update package.json#

{
    "name": "my-electron-ts-app",
    "version": "1.0.0",
    "description": "",
    "main": "dist/main.js",
    "scripts": {
        "build": "tsc",
        "start": "npm run build && electron ."
    },
    "devDependencies": {
        "electron": "^13.1.7",
        "typescript": "^4.4.3"
    }
}

3. Usage Methods#

Main Process (main.ts)#

import { app, BrowserWindow } from 'electron';
 
function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    });
 
    win.loadFile('index.html');
}
 
app.whenReady().then(() => {
    createWindow();
 
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});
 
app.on('window-all-closed', () => {
    if (process.platform!== 'darwin') {
        app.quit();
    }
});

Renderer Process (renderer.ts)#

document.addEventListener('DOMContentLoaded', () => {
    const heading = document.createElement('h1');
    heading.textContent = 'Hello from Electron TypeScript!';
    document.body.appendChild(heading);
});

HTML File (index.html)#

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Electron TypeScript App</title>
</head>
 
<body>
    <script src="dist/renderer.js"></script>
</body>
 
</html>

Running the Application#

npm start

4. Common Practices#

Separation of Concerns#

Keep the main process and renderer process code separate. The main process should handle window management and system-level tasks, while the renderer process should focus on the user interface and DOM manipulation.

Error Handling#

Implement proper error handling in both the main and renderer processes. For example, in the main process, you can handle errors when creating a browser window:

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

Use Type Definitions#

When using third-party libraries in your Electron TypeScript project, make sure to install the corresponding type definitions. For example, if you use axios for HTTP requests, install @types/axios.

npm install @types/axios --save - dev

5. Best Practices#

Code Splitting#

As your application grows, consider splitting your code into smaller modules. This makes the code more maintainable and easier to test. For example, you can create a separate module for handling file operations in the main process.

Testing#

Write unit and integration tests for your Electron TypeScript application. Tools like Jest can be used for testing TypeScript code. Install Jest and its TypeScript support:

npm install jest @types/jest ts - jest --save - dev

Create a jest.config.js file:

module.exports = {
    preset: 'ts - jest',
    testEnvironment: 'node'
};

Then you can write tests for your functions and components.

Security#

Follow security best practices when developing Electron applications. For example, use contextIsolation in the renderer process to prevent malicious code from accessing the main process APIs directly.

6. Conclusion#

An Electron TypeScript template provides a solid foundation for building cross-platform desktop applications with the benefits of static typing and a structured project setup. By understanding the fundamental concepts, following the usage methods, common practices, and best practices outlined in this blog, you can efficiently develop high-quality Electron applications using TypeScript. Whether you choose a boilerplate or a manual setup, the combination of Electron and TypeScript offers a powerful and reliable development experience.

7. References#