Front-end practice of using Electron to build desktop applications

Table of contents

1. What is Electron?

2. Project construction

2.1 Initialize the project

2.2 Install Electron

2.3 Create the main process

2.4 Create a rendering process

2.5 Update package.json

2.6 Start the application

3. Main process and rendering process

3.1 Main process

3.2 Rendering process

3.3 Communication between the main process and the rendering process

4. Interface design

4.1 Use HTML to build the interface

4.2 Using CSS to style the interface

4.3 Using Electron's preset styles

5. File system operations

5.1 Reading files

5.2 Write to file

6. Summary


Electron is a popular desktop application development framework that allows us to use front-end technologies (HTML, CSS, and JavaScript) to build cross-platform desktop applications. The advantage of Electron lies in its ease of use and flexibility, enabling front-end developers to quickly build powerful desktop applications. This blog will give you an in-depth understanding of how to use Electron to build desktop applications, including project construction, main process and rendering process, interface design, file system operations, etc., and demonstrate the practice of each step through actual code examples.

1. What is Electron?

Electron is an open source framework developed by GitHub for building cross-platform desktop applications. Based on Chromium and Node.js, it allows us to use web technologies (HTML, CSS, and JavaScript) to build desktop applications, while providing rich APIs and tools for accessing the underlying functions and resources of the operating system.

The architecture of Electron is very simple and clear: a main process (Main Process) is responsible for creating the application window and controlling the life cycle of the application, and multiple rendering processes (Renderer Process) are used to display the application interface and execute the front-end code. The main process and the rendering process communicate through IPC (Inter-Process Communication), so that they can cooperate with each other.

2. Project construction

Before we start using Electron to build desktop applications, we first need to set up the project environment. The following is a simple project construction process:

2.1 Initialize the project

First, we need to create a new project folder locally and initialize a new npm project in it.

 
 
mkdir my-electron-app
cd my-electron-app
npm init -y

2.2 Install Electron

Next, we need to install Electron as our project dependency.

 
 
npm install electron --save

2.3 Create the main process

Create a file called in the root directory of the project main.js, which is used to write the main process code.

 
 
const { app, BrowserWindow } = require('electron');

let mainWindow;

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  mainWindow.loadFile('index.html');
});

In the above code, we appcreate an application window through the module and load index.htmlthe file as the interface when the application is ready.

2.4 Create a rendering process

Create a file named at the root of your project index.htmlwhere you write your renderer code.

 
 
<!DOCTYPE html>
<html>
<head>
  <title>Electron App</title>
</head>
<body>
  <h1>Hello, Electron!</h1>
</body>
</html>

In the above code, we simply create an HTML page with a header.

2.5 Update package.json

Add the following content to package.jsonthe file to specify the entry file for Electron main.js.

 
 
{
  "main": "main.js",
  ...
}

2.6 Start the application

Finally, we can start our Electron application with the following command.

 
 
npx electron .

If everything goes well, you will see a "Hello, Electron!" interface in the window, which means your project has been successfully built and running.

3. Main process and rendering process

In the previous section, we simply created an Electron application and implemented a simple interface. In this section, we'll dig into the concepts of the main process and the render process, and learn how to communicate between them.

3.1 Main process

The main process is the core of the Electron application, which is responsible for creating the application window and controlling the life cycle of the application. In the code in the previous section, we used appthe and BrowserWindowmodule to create the main process. The main process is an ordinary Node.js process that has access to the underlying functions and resources of the operating system.

3.2 Rendering process

The rendering process is used to display the interface of the application and execute the front-end code. In the code in the previous section, we used loadFilethe method to index.htmlload the file into the application window and display "Hello, Electron!" in it. The renderer process is an ordinary web page that uses HTML, CSS, and JavaScript to build the interface and handle user interaction.

3.3 Communication between the main process and the rendering process

The main process and the rendering process run separately, and they cannot directly access each other's code and variables. However, in Electron, we can communicate between the main process and the renderer process via IPC. IPC allows us to pass messages between the main process and the renderer process, and perform corresponding operations there.

In the main process, we can use ipcMainmodules to receive and process messages sent by the renderer process.

 
 
// main.js

const { app, BrowserWindow, ipcMain } = require('electron');

let mainWindow;

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  mainWindow.loadFile('index.html');

  ipcMain.on('message', (event, arg) => {
    console.log(arg); // 打印渲染进程发送的消息
    event.reply('reply', 'Hello from main process!'); // 回复消息给渲染进程
  });
});

In the rendering process, we can use ipcRendererthe module to send messages to the main process and handle the reply from the main process.

 
 
// index.html

<!DOCTYPE html>
<html>
<head>
  <title>Electron App</title>
</head>
<body>
  <h1>Hello, Electron!</h1>
  <button id="sendBtn">Send Message</button>
  <div id="replyMsg"></div>
  <script>
    const { ipcRenderer } = require('electron');

    document.getElementById('sendBtn').addEventListener('click', () => {
      ipcRenderer.send('message', 'Hello from renderer process!');

      ipcRenderer.on('reply', (event, arg) => {
        document.getElementById('replyMsg').innerText = arg;
      });
    });
  </script>
</body>
</html>

ipcRendererIn the above code, we listen to the button click event in the renderer process, and use the module to send a "Hello from renderer process!" message to the main process when the button is clicked . Then, listen to the event in the main process message, print the message content when receiving the message, and event.replyreply the message to the rendering process through the method. After the rendering process receives the reply from the main process, it displays the reply content on the page.

Through IPC, we can communicate flexibly between the main process and the rendering process to realize complex application logic and interaction.

4. Interface design

In front-end development, interface design is a very important link. Good interface design can improve user experience and application value. In this section, we will learn how to use HTML and CSS to design the interface of Electron application.

4.1 Use HTML to build the interface

In Electron, we can use HTML to build the interface of the application. HTML is a markup language used to define the structure and content of an application.

 
 
<!DOCTYPE html>
<html>
<head>
  <title>Electron App</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Hello, Electron!</h1>
  <button id="sendBtn">Send Message</button>
  <div id="replyMsg"></div>
  <script src="renderer.js"></script>
</body>
</html>

In the above code, we have created an HTML page that contains a title, a button and a message box.

4.2 Using CSS to style the interface

In Electron, we can use CSS to style the interface of the application. CSS is a style sheet language used to define the appearance and layout of an application.

 
 
/* styles.css */

body {
  font-family: Arial, sans-serif;
  text-align: center;
  background-color: #f0f0f0;
}

h1 {
  color: #333;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
}

#replyMsg {
  margin-top: 20px;
  font-size: 18px;
  color: #007bff;
}

In the above code, we define some common CSS styles, such as font, color, button style, etc.

4.3 Using Electron's preset styles

In addition to custom styles, Electron also provides some preset styles that can help us quickly build a beautiful interface. You can see the details of these preset styles in Electron's documentation.

 
 
<!-- 使用预置样式 -->
<link rel="stylesheet" href="https://unpkg.com/electron@latest/dist/electron.css">

Through reasonable HTML and CSS design, we can create a unique and user-friendly application interface.

5. File system operations

In desktop applications, file system manipulation is a common requirement. In this section, we will learn how to use Node.js fsmodules to perform file system operations, and practice these operations in Electron applications.

5.1 Reading files

We can use fs.readFilemethod to read file content.

 
 
// main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');

ipcMain.on('readFile', (event, filePath) => {
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      event.reply('fileData', { success: false, data: null, error: err.message });
    } else {
      event.reply('fileData', { success: true, data: data, error: null });
    }
  });
});
 
 
// index.html

<!DOCTYPE html>
<html>
<head>
  <title>Electron App</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Hello, Electron!</h1>
  <button id="readFileBtn">Read File</button>
  <div id="fileData"></div>
  <script src="renderer.js"></script>
</body>
</html>
 
 
// renderer.js

const { ipcRenderer } = require('electron');

document.getElementById('readFileBtn').addEventListener('click', () => {
  const filePath = 'path/to/your/file.txt';
  ipcRenderer.send('readFile', filePath);
});

ipcRenderer.on('fileData', (event, data) => {
  if (data.success) {
    document.getElementById('fileData').innerText = data.data;
  } else {
    document.getElementById('fileData').innerText = 'Error: ' + data.error;
  }
});

In the above code, we use fs.readFilethe method to read the file content of the specified path, and send the result to the rendering process through IPC. After the rendering process receives the file content, it displays the content on the page.

5.2 Write to file

We can use fs.writeFilemethod to write file content.

 
 
// main.js

ipcMain.on('writeFile', (event, data) => {
  const filePath = 'path/to/your/file.txt';
  fs.writeFile(filePath, data, 'utf8', (err) => {
    if (err) {
      event.reply('writeResult', { success: false, error: err.message });
    } else {
      event.reply('writeResult', { success: true, error: null });
    }
  });
});
 
 
// index.html

<!DOCTYPE html>
<html>
<head>
  <title>Electron App</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Hello, Electron!</h1>
  <button id="writeFileBtn">Write File</button>
  <div id="writeResult"></div>
  <script src="renderer.js"></script>
</body>
</html>
 
 
// renderer.js

document.getElementById('writeFileBtn').addEventListener('click', () => {
  const data = 'Hello, Electron!';
  ipcRenderer.send('writeFile', data);
});

ipcRenderer.on('writeResult', (event, result) => {
  if (result.success) {
    document.getElementById('writeResult').innerText = 'Write Success!';
  } else {
    document.getElementById('writeResult').innerText = 'Error: ' + result.error;
  }
});

In the above code, we use fs.writeFilethe method to write the specified data to the file, and send the written result to the rendering process through IPC. After the rendering process receives the writing result, it displays the result on the page.

Through the file system operation, we can realize the data storage and reading of the application, and realize more interesting functions.

6. Summary

This blog introduces the front-end practice of using Electron to build desktop applications. We learned the construction of Electron, the main process and rendering process, interface design, file system operation, packaging and publishing, and demonstrated the practice of each step through actual code examples.

Guess you like

Origin blog.csdn.net/m0_68036862/article/details/132040964