Welcome to the core of your Electron application! Just like an orchestra needs a conductor to keep everything in harmony, your Electron app has a 'main process' that orchestrates its behavior and manages its lifecycle. Think of it as the brain of your desktop application.
The main process is a Node.js runtime. This is crucial because it means you have access to all the powerful Node.js modules and APIs. You can interact with the operating system, manage files, create native menus, and much more. It's the gateway to your application's desktop capabilities.
Every Electron app has exactly one main process. It's the first process to start when you launch your application and the last one to exit.
One of the primary responsibilities of the main process is to create and manage browser windows. These windows are where your web content (HTML, CSS, JavaScript) will be displayed. The main process uses the BrowserWindow module from Electron to instantiate these windows.
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true // Be cautious with this in production
}
});
mainWindow.loadFile('index.html');
mainWindow.on('closed', function () {
mainWindow = null;
});
}In the code snippet above, we see the main process using require('electron') to access Electron's core modules. It then creates a new BrowserWindow, loads an index.html file into it, and sets up an event listener for when the window is closed.
The main process also handles application-level events. This includes things like when the application is ready to start, when all windows are closed, or when the user tries to quit the application. You'll often see listeners for these events in your main process code.
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});