Electron Builder with TypeScript: A Comprehensive Guide

Electron is an open - source framework that allows developers to build cross - platform desktop applications using web technologies such as HTML, CSS, and JavaScript. Electron Builder, on the other hand, is a powerful tool for packaging and distributing Electron applications. TypeScript, a superset of JavaScript, adds static typing to the language, which helps catch errors early in the development process and makes the code more maintainable. Combining Electron Builder with TypeScript can enhance the development experience and result in high - quality desktop applications.

Table of Contents

  1. Fundamental Concepts
    • What is Electron?
    • What is Electron Builder?
    • What is TypeScript?
  2. Setting up the Project
  3. Usage Methods
    • Writing TypeScript code in an Electron project
    • Using Electron Builder to package the application
  4. Common Practices
    • Directory Structure
    • Handling Dependencies
  5. Best Practices
    • Error Handling
    • Code Organization
  6. Conclusion
  7. References

Fundamental Concepts

What is Electron?

Electron is a framework developed by GitHub. It uses Chromium and Node.js to create desktop applications. With Electron, developers can use web technologies to build applications that run on Windows, macOS, and Linux. For example, applications like Visual Studio Code, Slack, and Discord are built using Electron.

What is Electron Builder?

Electron Builder is a complete solution to package and distribute your Electron application with “auto update” support out of the box. It can create installers for different platforms, manage application icons, and handle code signing.

What is TypeScript?

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It adds types to JavaScript, which helps in writing more robust and maintainable code. For example, in JavaScript, a variable can hold any type of value, but in TypeScript, you can define the type of a variable, like let num: number = 10;

Setting up the Project

  1. Create a new directory for your project and navigate into it:
mkdir electron - typescript - app
cd electron - typescript - app
  1. Initialize a new Node.js project:
npm init -y
  1. Install Electron, Electron Builder, and TypeScript:
npm install electron electron - builder typescript --save - dev
  1. Initialize a TypeScript configuration file:
npx tsc --init

In the tsconfig.json file, you can make the following changes:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    }
}

Usage Methods

Writing TypeScript code in an Electron project

  1. Create a src directory in your project and add a main.ts file:
import { app, BrowserWindow } from 'electron';

let mainWindow: BrowserWindow | null;

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

    mainWindow.loadFile('index.html');

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

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

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

app.on('window - all - closed', () => {
    if (process.platform!== 'darwin') app.quit();
});
  1. Create an index.html file in the root directory:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF - 8">
    <meta name="viewport" content="width=device - width, initial - scale = 1.0">
    <title>Electron TypeScript App</title>
</head>

<body>
    <h1>Hello, Electron with TypeScript!</h1>
</body>

</html>
  1. Compile the TypeScript code:
npx tsc
  1. Run the Electron application:
npx electron dist/main.js

Using Electron Builder to package the application

  1. Add a build script to your package.json file:
{
    "scripts": {
        "build": "npx tsc && electron - builder"
    },
    "build": {
        "appId": "com.example.electron - typescript - app",
        "productName": "Electron TypeScript App",
        "directories": {
            "output": "dist"
        },
        "win": {
            "target": [
                "nsis"
            ]
        },
        "mac": {
            "target": [
                "dmg"
            ]
        },
        "linux": {
            "target": [
                "deb"
            ]
        }
    }
}
  1. Run the build script:
npm run build

This will create installers for different platforms in the dist directory.

Common Practices

Directory Structure

A common directory structure for an Electron TypeScript project is as follows:

electron - typescript - app/
├── src/
│   ├── main.ts
│   ├── renderer/
│       ├── renderer.ts
├── index.html
├── package.json
├── tsconfig.json
├── dist/
    ├── main.js
    ├── renderer.js
    ├── [platform - specific installers]

Handling Dependencies

  • Use npm or yarn to manage your project dependencies.
  • Separate development dependencies (like TypeScript and Electron Builder) from production dependencies.
  • Keep your package.json file up - to - date and use version ranges carefully.

Best Practices

Error Handling

  • Use try - catch blocks in your TypeScript code to handle errors gracefully. For example:
try {
    // Some code that might throw an error
    const result = JSON.parse('invalid json');
} catch (error) {
    console.error('Error parsing JSON:', error);
}
  • In Electron, handle uncaught exceptions globally in the main process:
process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
});

Code Organization

  • Split your code into smaller, reusable modules. For example, you can create separate modules for handling different aspects of your application, like window management, API calls, etc.
  • Follow a consistent naming convention for your variables, functions, and classes.

Conclusion

Combining Electron Builder with TypeScript can significantly improve the development process of cross - platform desktop applications. TypeScript adds static typing to your code, making it more reliable and easier to maintain. Electron Builder simplifies the packaging and distribution of your application. By following the concepts, usage methods, common practices, and best practices outlined in this blog, you can build high - quality Electron applications with TypeScript efficiently.

References