📜 ⬆️ ⬇️

Electron: develop desktop applications using HTML, CSS and JavaScript

Is it possible to create desktop applications using HTML, CSS and JavaScript? The author of the article, the translation of which we are publishing today, gives an affirmative answer to this question. Here he will talk about how, using web technologies and using the capabilities of the Electron framework, to create cross-platform applications for desktop operating systems.



Electron


Electron is a framework for developing desktop applications using HTML, CSS and JavaScript. Such applications can work on different platforms. Among them - Windows, Mac and Linux.

At the core of Electron are Chromium and Node.js projects, combined into a single environment that provides applications. This makes it possible to use web technologies in the development of desktop programs.

Electron is a serious project that was used to create many popular applications. Among them are Skype and Discord messengers, editors for Visual Studio Code and Atom code, as well as more than 700 applications that are published on the Electron website.

Electron forge


To develop an application using Electron, this framework must be configured. This also applies to those cases when the application plans to use other frameworks or libraries, for example, Angular, React, Vue, or something else.

The command line tool Electron Forge allows you to seriously simplify the process of setting up Electron. It provides the developer with application templates based on Angular, React, Vue, and other frameworks. This saves the programmer from having to configure everything manually.

In addition, Electron Forge simplifies the assembly and packaging of the application. In fact, this tool also has many other useful features, which can be found in its documentation .

Consider the process of developing a simple application on Electron using Electron Forge.

Preliminary preparation


In order to start developing Electron applications using Electron Forge, you will need a system with the Node.js platform installed. You can download it here .

For the global installation of Electron Forge, you can use the following command:

npm install -g electron-forge 

Creating a template application


In order to create a template application using Electron Forge, run the following command:

 electron-forge init simple-desktop-app-electronjs 

This command initializes a new application project whose name is simple-desktop-app-electronjs . It will take some time to execute this command. After the template application is created, you can start it like this:

 cd simple-desktop-app-electronjs npm start 

Here we go to its folder and call the corresponding npm script.

After this, a window should open, the contents of which are similar to what is shown in the following figure.


Application window created by means of Electron Forge

Let's talk about how this application is arranged.

Template Application Structure


The materials that make up the sample application created by Electron Forge tools are represented by a set of files and folders. Consider the most important parts of the application.

PackageFile package.json


This file contains information about the created application, its dependencies. It contains a description of several scripts, one of which, start , was used to launch the application. New scripts in this file can be added independently.

In the section of the config.forge file config.forge can find specific settings for Electron. For example, the section make_targets contains subsections describing the goals of building a project for Windows platforms ( win32 ), Mac ( darwin ) and Linux ( linux ).

In package.json you can find the following entry: "main": "src/index.js" , which indicates that the entry point to the application is the file located at src/index.js .

▍File src / index.js


According to the information found in package.json , the main application script is index.js . The process that executes this script is called the main process. This process controls the application. It is used in the formation of the application interface, which is based on the capabilities of the browser. It is also responsible for interaction with the operating system. The application interface is represented by web pages. Rendering of web pages and the execution of their code is the responsibility of the rendering process (renderer process).

▍Main process and rendering process


The goal of the main process is to create browser windows using an instance of the BrowserWindow object. This object uses the rendering process to organize the operation of web pages.

Each Electron application can have only one main process, but there can be several rendering processes. In addition, it is possible to establish interaction between the main process and rendering processes, we will not talk about this here, however. Here is a diagram of the architecture of an Electron-based application, which presents the main process and two rendering processes.


Electron application architecture

This diagram shows two web pages - index.html and abcd.html . In our example, only one page will be used, represented by the index.html file.

SFile src / index.html


The script from index.js loads the index.html file into a new instance of BrowserWindow . If we describe this process in simple words, it turns out that index.js creates a new browser window and loads the page described in the index.html file into it. This page runs in its own rendering process.

▍Display the code file index.js


The code for the index.js file index.js well commented. Consider its most important parts. So, the following code snippet of the createWindow() function creates an instance of the BrowserWindow object, loads the index.html file into the window represented by this object, and opens the developer tools.

 // Создаём окно браузера. mainWindow = new BrowserWindow({ width: 800, height: 600, }); // и загружаем в него файл приложения index.html. mainWindow.loadURL(`file://${__dirname}/index.html`); // Открываем инструменты разработчика. mainWindow.webContents.openDevTools(); 

In the finished application, the line of code that opens the developer tools makes sense to comment out.

In the code for this file, the app object is often found. For example, in the following snippet:

 // Этот метод будет вызван после того, как Electron завершит // инициализацию и будет готов к созданию окон браузера. // Некоторые API можно использовать только после возникновения этого события. app.on('ready', createWindow); 

The app object is used to manage the life cycle of the application. In this case, after the initialization of Electron is completed, the function responsible for creating the application window is called.

The app object is also used to perform other actions when various events occur. For example, it can be used to organize the execution of certain operations before closing an application.

Now that we have learned about the structure of an Electron application, consider an example of developing such an application.

Development of desktop application - temperature converter


As a basis for this training application, we will use the previously created template project simple-desktop-app-electronjs .

First, install the package Bootstrap, using the following command in the project folder:

 npm install bootstrap --save 

Now replace the code in the index.html file with the following:

 <!DOCTYPE html> <html> <head>   <meta charset="utf-8">   <title>Temperature Converter</title>   <link rel="stylesheet" type="text/css" href="../node_modules/bootstrap/dist/css/bootstrap.min.css"> </head> <body>   <h1>Temperature Converter</h1>   <div class="form-group col-md-3">     <label for="usr">Celcius:</label>     <input type="text" class="form-control" id="celcius" onkeyup="celciusToFahrenheit()">   </div>   <div class="form-group col-md-3">     <label for="pwd">Fahrenheit:</label>     <input type="text" class="form-control" id="fahrenheit" onkeyup="fahrenheitToCelcius()">   </div>   <script src='./renderer.js'></script> </body> </body> </html> 

Here’s how this code works:

  1. Here you create a text field with the identifier celcius . When a user enters a certain value in this field, which should be a temperature in degrees Celsius, the function celciusToFahrenheit() called.
  2. The text field with the identifier fahrenheit , also created in this code, receives data from the user, which must be a temperature in degrees Fahrenheit, after which the function fahrenheitToCelcius() called.
  3. The celciusToFahrenheit() function converts the temperature, expressed in degrees Celsius and entered in the celcius field, into temperature in degrees Fahrenheit, and then outputs what it did, in the field fahrenheit .
  4. The fahrenheitToCelcius() function performs the inverse transformation — it takes a temperature value, expressed in degrees Fahrenheit and entered in the fahrenheit field, converts it to a value expressed in degrees Celsius, and then writes what it did, in the сelcius field.

The two functions that we just talked about are declared in the renderer.js file. This file must be created in the src folder and put the following code into it:

 function celciusToFahrenheit(){   let celcius = document.getElementById('celcius').value;   let fahrenheit = (celcius* 9/5) + 32;   document.getElementById('fahrenheit').value = fahrenheit; } function fahrenheitToCelcius(){   let fahrenheit = document.getElementById('fahrenheit').value;   let celcius = (fahrenheit - 32) * 5/9   document.getElementById('celcius').value = celcius; } 

As you can see, each of these functions will receive the value of the corresponding field on the page, convert the resulting value, and write what happened in another field. The functions are very simple, in particular, the values ​​with which they work are not checked in any way, but in our case it does not matter.

We assume that the application is ready. Test it.

Application launch


In order to start the application, use the following command:

 npm start 

After its successful execution, an application window will open with the following contents.


Converter Application Window

Experiment with the application by entering different values ​​in the fields.
Now that we’ve seen that the application works as expected, it’s time to pack it.

Packaging application


To pack an application, use the following command:

 npm run package 

The system will take some time to execute this command. After her work is completed, look in the out folder, which will appear in the project folder.

The experiment on the development of the Electron-application, described here, was conducted on a computer running Windows. Therefore, the folder simple-desktop-app-electronjs-win32-x64 was created in the out folder. In this folder, among other things, you can find the .exe file of the application. In our case, it is called simple-desktop-app-electronjs.exe . To launch an application, simply double-clicking on this file is enough.

Let us analyze the name of the folder where the executable file of the application is located. Namely, it is built on the pattern of имя приложения - платформа - архитектура . In our case, its structure is revealed as follows:


Note that when invoking the npm run package command without parameters, by default, an executable file of the application is created for the platform used during development.

Suppose you need to package an application for some other platform and architecture. To do this, you can use the advanced version of the above command. The structure of this command looks like this:

 npm run package -- --platform=<platform> arch=<architecture> 

For example, to build an application package for Linux, you can use the following command:

 npm run package -- --platform=linux --arch=x64 

After its work is completed, the simple-desktop-app-electronjs-linux-x64 directory with the corresponding contents will appear in the out project folder.

Creating application installation files


To create an application installation file, use the following command:

 npm run make 

The results of her work will be in the out folder you already know. Namely, the launch of this command in the above form on a Windows machine will lead to the creation of an installation file for a Windows application in the out\make\squirrel.windows\x64 folder. Like the package command, the make , invoked without parameters, creates an installer for the platform used during development.

Results


In this material we covered the basics of the architecture of Electron-applications and wrote a simple program . If you were thinking about developing your own application based on Electron, now you have the basic knowledge, having independently expanded and expanded it, you can create what you want.

Dear readers! Do you use an Electron framework for developing desktop applications?

Source: https://habr.com/ru/post/436466/