Electron - Day2, build an entry case from scratch

1. Goals

Learn the official example and build HelloWorld step by step.
Understand the basic structure of Electron.

https://www.electronjs.org/zh/docs/latest/tutorial/quick-start

2. Project Framework

Install yarn.
Create package.json.
Install electron.

npm install --global yarn

yarn init -y

yarn add electron --dev

Create a startup script.

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

Running the script should give an error.
Because there is no entry js.

insert image description here

3. Introductory case

Create index.html.

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport"
		  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
</head>
<body>
<h1>你好,世界!</h1>
</body>
</html>

In the main directory, create main.js.

const {
    
     app, BrowserWindow } = require('electron')
const createWindow = () => {
    
    
	const win = new BrowserWindow({
    
    
		width: 800,
		height: 600
	})
	win.loadFile('./src/index.html')
}
app.whenReady().then(() => {
    
    
	createWindow()
})

Change the entry in package.json to main.js.

"main": "main.js",

Start the script.

insert image description here

4. Improve some details

Exit after closing all windows

app.on('window-all-closed', () => {
    
    
	if (process.platform !== 'darwin') app.quit()
})

Open a window on start (compatible)

app.whenReady().then(() => {
    
    
	createWindow()
	app.on('activate', () => {
    
    
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})
})

5. Preload

(To be added)

6. Generate exe

Tools: https://www.electronforge.io/

This is a full process tool, so next time you can use it to create ElectronApp directly.

yarn add --dev @electron-forge/cli

yarn electron-forge import

npx run make 

Effect:

insert image description here
exe in the out folder.

insert image description here

7. Quick build

There are many ways to quickly build, I choose the one that packs the exe, Electron Forge.

yarn create electron-app my-app

Complete tools:

insert image description here
There are also debugging tools during development:

insert image description here

Guess you like

Origin blog.csdn.net/qq_37284843/article/details/123790302