Making Your First Electron Application

July 12, 2024

In this blog we are exploring how to start making your own electron application. Electron is a free and open-source software framework developed and maintained by OpenJS Foundation. The framework is designed to create desktop applications using web technologies that are rendered using a version of the Chromium browser engine and a back end using the Node.js runtime environment

Dependencies:

  • Node Js
  • NPM Package Manager
  • HTML
  • CSS
  • Visual Studio Code or Any IDE

Creating Your First Application

Every electron app follows the same structure as the nodejs applications it would be started by creating a folder and initializing the npm package.

mdkdir my-electron-app && cd my-electron-app

You can replace the my-electron-app with the folder name of your choice. Next to this is to initialize the application with the init command

npm init

This would make a folder named node modules inside the folder that you created in this case we created the folder named my-electron-app a folder named node_modules would appear in the file directory.

[!NOTE] Take Note It is very important to add the node_modules folder in your .gitignore file if you are going to use github for storing the repository and the version control. This allow the application to not exceed in its minimum upload per push witch is 100mb.

Now there would be also some files that you could see and some files that you might need to add in the directory you have.

You need to create a file named main.js as this file is our entry point. The main.js is the js file that would handle the creation of the window and interactions that could be made with the user.

Also you need to configure this to your package.json and you must check its content if it looks like this:

{  
"name": "my-electron-app",  
"version": "1.0.0",  
"description": "Hello World!",  
"main": "main.js",  
"author": "Jane Doe",  
"license": "MIT"  
}

Installing Electron

To install electron simply just type in your terminal this command:

npm install --save-dev electron

it is important that you must be on the directory of your folder when you are installing this to allow the file to enter inside the node_modules folder.

Now to execute the electron you need to add this to the package.json config

{  
"scripts": {  
"start": "electron ."  
}  
}

This would look like this:

{  
	"name": "my-electron-app",  
	"version": "1.0.0",  
	"description": "Hello World!",  
	"main": "main.js",  
	"author": "Jane Doe",  
	"license": "MIT"  
}
	{  
		"scripts": {  
		"start": "electron ."  
	}  
}

This start command would allow you to open the app in the development mode and simply can use it in the terminal by typing:

npm start

This would start your electron project but nothing could just pop up yet because you haven't initialized the needed files for this you need to have file structure like this first:

/your-project
|-- /css
|   |-- styles.css
|-- /js
|   |-- preload.js
|   |-- renderer.js
|-- main.js
|-- index.html

In the index.html you can have your simple template such as:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

And on the main.js you could have:

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('node:path')

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

This would crate a 800x600 window and would exit when you close the window

Meanwhile the preload.js

window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})

A preload script runs before the renderer process is loaded, and has access to both renderer global (e.g. window and document) and a Node.js environment. The above code accesses the Node.js process.versions object and runs a basic replaceText helper function to insert the version numbers into the HTML document.

And there you now have simple working locally hosted electron application.