Electron has two main types of processes: the main process and the renderer process.
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.
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.
One of the easiest ways to set up an Electron TypeScript project is to use a boilerplate like electron - forge
with TypeScript support.
npm install -g electron-forge
electron-forge init my - electron - ts - app --template=typescript
cd my - electron - ts - app
If you prefer a manual setup, here are the steps:
mkdir my - electron - ts - app
cd my - electron - ts - app
npm init -y
npm install electron typescript --save - dev
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"]
}
Create a src
directory and add a main.ts
file for the main process and a renderer.ts
file for the renderer process.
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"
}
}
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.ts
)document.addEventListener('DOMContentLoaded', () => {
const heading = document.createElement('h1');
heading.textContent = 'Hello from Electron TypeScript!';
document.body.appendChild(heading);
});
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>
npm start
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.
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);
}
}
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
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.
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.
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.
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.