当前位置:网站首页>Getting started with electron
Getting started with electron
2022-07-19 19:03:00 【Hua Weiyun】
Electron It's a use JavaScript、HTML and CSS Building a framework for desktop applications . The embedded Chromium and Node.js To The binary Electron Allows you to keep a JavaScript Code base and create stay Windows Cross platform applications running on macOS and Linux—— No need for local development Experience .
Quick start
This article will use Electron Create a minimalist Hello World The application will take you step by step Electron The past and this life ,
Through this tutorial , Yours app A browser window will open , To show the currently running Chromium, Node.js And Electronweb And other version information web Interface
In the use of Electron Before development , You need to install Node.js. We suggest you use the latest LTS edition .
Please use the pre built for your platform Node.js Installer to install , otherwise , You may encounter problems that are incompatible with different development tools .
To check Node.js Is it installed correctly , Please enter the following command on your terminal :
node -vnpm -v
These two commands should output Node.js and npm Version information for .
Create your app
Use scaffolding to create
Electron Applications follow the same rules as other Node.js The same structure of the project . First create a folder and initialize npm package .
npm
Yarn
mkdir my-electron-app && cd my-electron-appnpm inityarn add --dev electron
init
The initialization command prompts you to set some values in the project initialization configuration , There are several rules to follow :
entry point
Should bemain.js
.author
Anddescription
It can be any value , But for the Application packaging Are mandatory .
Yours package.json
The file should look like this :
{ "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "main.js", "author": "Jane Doe", "license": "MIT"}
then , take electron
The package is installed into the development dependency of the application .
npm
Yarn
npm install --save-dev electron
Last , You want to be able to perform Electron As shown below , In your [package.json
In the configuration file scripts
Add a start
command :
{ "scripts": { "start": "electron ." }}
start
Command allows you to open your application in development mode
npm
Yarn
npm start
yarn start# couldn't auto-convert command
Be careful : This script will tell Electron Run... At the root of your project here , Your application will immediately throw an error to remind you that it cannot find the application to run
Run the main process
whatever Electron The entry to the application is main
file . This file controls The main process , It runs in a complete Node.js Environment , Responsible for controlling the life cycle of your application , Show native interface , Perform special operations and manage the render process ( I'll tell you more later ).
During execution ,Electron Will be based on the application of package.json
Under configuration main
Field to find this file
To initialize this main
file , You need to create a directory in the root of your project called main.js
Empty file .
Be careful : If you run again at this time
start
command , Your application will no longer throw any errors ! However , It won't do anything because we haven't beenmain.js
Add any code in .
Create a page
Before we can create a window for our application , We need to create the content loaded into the window first . stay Electron in , The content displayed in each window can be local HTML file , It can also be a remote url.
In this tutorial , You will use local HTML The way . Create a project named index.html
The file of :
<!DOCTYPE html><html> <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>
Be careful : In this HTML In the text , You will find that the version number is missing from the body text . Later we will use JavaScript Insert them dynamically .
Open your page in a window
Now you have a page , Load it into the application window . Do that , You need Two Electron modular :
app
modular , It controls the event lifecycle of the application .BrowserWindow
modular , It creates and manages applications window .
Because the main process is running Node.js, You can go to main.js The file header imports them as CommonJS modular :
const { app, BrowserWindow } = require('electron')
then , Add one createWindow()
Methods to index.html
Load in a new BrowserWindow
example .
const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile('index.html')}
next , call createWindow()
Function to open your window .
stay Electron in , Only in app
Modular ready
The browser window cannot be created until the event is fired . You can use the app.whenReady()
API To monitor this event . stay whenReady()
Call after success createWindow()
.
app.whenReady().then(() => { createWindow()})
Be careful : here , Your E-application should be successful Open the window that shows your page !
Manage the life cycle of windows
Although you can now open a browser window , But you also need some extra template code to make it look more like native to each platform . The application window is in each OS There are different behaviors under different circumstances ,Electron Will be in app It's up to the developers to implement these conventions .
generally speaking , You can use process
Overall platform
Property to run code specifically for certain operating systems .
Exit the app when all windows are closed (Windows & Linux)
stay Windows and Linux On , Closing all windows usually exits an application completely .
To achieve this , You need to monitor app
Modular 'window-all-closed'
event . If the user is not macOS(darwin
) Run the program on , Call app.quit()
.
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit()})
If no window is open, open a window (macOS)
When Linux and Windows The app exited when there was no window open ,macOS Applications usually continue to run even when no windows are open , And when you activate the app when no window is available, a new window will open .
In order to achieve this feature , monitor app
Modular activate
event . If no browser window is open , Call createWindow()
Method .
Because windows can't be in ready
Create before the event , You should only listen after your app is initialized activate
event . Through your existing whenReady()
Attach your event listener to the callback to do this .
app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() })})
Be careful : here , Your Windows controls should be fully functional !
Access from the render through preloaded scripts Node.js.
Now? , The last thing to do is output Electron Version number and its dependencies to your web On the page .
In the main process through Node Overall situation process
Object access to this information is trivial . However , You can't edit directly in the main process DOM, Because it can't access the render file
Context . They exist in completely different processes !
This is going to be Preloading Where scripts come in handy when connecting to renderers . The preload script loads before the render process loads , And have access to two Render global ( for example window
and document
) and Node.js Environmental Science .
Create a file called preload.js
The new script for is as follows :
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]) }})
Code access above Node.js process.versions
object , And run a basic replaceText
The auxiliary function inserts the version number into HTML In the document .
To attach this script to the render flow , Please put it in your existing BrowserWindow
The constructor passes the preloaded script in the path into webPreferences.preload
Options .
// include the Node.js 'path' module at the top of your fileconst path = require('path')// modify your existing createWindow() functionconst createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) win.loadFile('index.html')}// ...
Two are used here Node.js Concept :
__dirname
The string points to the path where the script is currently executing ( In this case , It points to the root folder of your project ).path.join
API Join multiple paths together , Create a cross platform path string .
We use a relative currently executing JavaScript Path to file , In this way, your relative path will be effective in both development mode and packaging mode .
Add features to your web content
At the moment , You may want to know how to add more features to your application .
For any interaction with your web content , You want to add scripts to your render process . Because the render is running normally Web Environment , So you can go to index.html
File close </body>
Add one before the tag <script>
label , To include any script you want :
<script src="./renderer.js"></script>
renderer.js
The code contained in can be used next in the same way as the front-end development JavaScript API And tools . For example, using webpack
Package and minimize your code , Or use React To manage your user interface .
review
After completing the above steps , You should have a fully functional Electron Program , As shown below :
The complete code is as follows :
// main.js// Modules to control application life and create native browser windowconst { app, BrowserWindow } = require('electron')const path = require('path')const createWindow = () => { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) // load index.html mainWindow.loadFile('index.html') // Open development tools // mainWindow.webContents.openDevTools()}// This program will be in Electron End initialization // And when creating a browser window // part API stay ready Use... Only after the event is triggered .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() })})// except macOS Outside , Exit the program when all windows are closed . 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. It can also be split into several files , And then use require Import .
// preload.js// all Node.js API Can be used during preloading .// It has Chrome Expand the same sandbox .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]) }})
<!--index.html--><!DOCTYPE html><html> <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>. <!-- You can also run other files in this process --> <script src="./renderer.js"></script> </body></html>
Summarize all the steps we have done :
We started a Node.js Program , And will Electron Add as dependency .
We created one
main.js
Script to run our main process , It controls our application And in Node.js Running in the environment . In this script , We use Electron Ofapp
andBrowserWindow
Module to create a browser window , In a separate process ( Renderers ) Display web page content .To access Node.js Some functions of , We are
BrowserWindow
A preloaded script is attached to the constructor of .
Package and distribute your application
The quickest way to package is to use Electron Forge.
take Electron Forge Add to the development dependencies of your application , And use it "import" Command settings Forge Scaffolding :
npm
Yarn
npm install --save-dev @electron-forge/clinpx electron-forge import Checking your system Initializing Git Repository Writing modified package.json file Installing dependencies Writing modified package.json file Fixing .gitignoreWe have ATTEMPTED to convert your app to be in a format that electron-forge understands.Thanks for using "electron-forge"!!!
yarn add --dev @electron-forge/clinpx electron-forge import Checking your system Initializing Git Repository Writing modified package.json file Installing dependencies Writing modified package.json file Fixing .gitignoreWe have ATTEMPTED to convert your app to be in a format that electron-forge understands.Thanks for using "electron-forge"!!!
Use Forge Of make
Command to create a distributable Application :
npm
Yarn
npm run make> [email protected] make /my-electron-app> electron-forge make Checking your system Resolving Forge ConfigWe need to package your application before we can make it Preparing to Package Application for arch: x64 Preparing native dependencies Packaging ApplicationMaking for the following targets: zip Making for target: zip - On platform: darwin - For arch: x64
yarn run make> [email protected] make /my-electron-app> electron-forge make Checking your system Resolving Forge ConfigWe need to package your application before we can make it Preparing to Package Application for arch: x64 Preparing native dependencies Packaging ApplicationMaking for the following targets: zip Making for target: zip - On platform: darwin - For arch: x64
Electron-forge Will create out
Folder , Your software package will be found there :
// Example for macOSout/├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip├── ...└── out/my-electron-app-darwin-x64/my-electron-app.app/Contents/MacOS/my-electron-app
边栏推荐
- Relationship between web page and browser (0)
- How does the JVM know that an object should be recycled?
- 指定初始化和便利初始化
- oracle远程连接配置
- 元宇宙、NFT数字藏品是什么?
- DRF--validators检验函数,单字段校验,多字段联合校验
- Design idea of third-party system docking (case sharing)
- Go 语言逃逸分析
- Shell Programming Notes (III)
- DRF--Router路由器对象自动生成路由,自定义action生成路由
猜你喜欢
DRF--视图集viewsets,具体通用视图viewsets .ModelViewSet
System security and Application
MySQL复合索引示例
C language document - document operation
网页与浏览器的关系(0)
DRF--Mixin拓展类,CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
Will Web3 reshape Internet business?
类视图---->类视图集 演进继承关系图 总结
Sanjian capital lost and resumed its business: its impact on the encryption market is nearing the end
Analysis of iterative and recursive time complexity
随机推荐
gstreamer之plugin_init
The difference between beanfactory and factorybean (introductory learning)
C # introductory series (23) -- partial classes and abstract classes
How many of the 14 market bottom signals have been confirmed?
指定初始化和便利初始化
DRF -- validators verification function, single field verification, multi field joint verification
经济日报:莫把数字藏品当“生财”产品
C语言动态内存篇——动态内存管理
BeanFactory与FactoryBean的区别(入门学习)
How does the JVM know that an object should be recycled?
Search engines fall in Web3.0?
OpenHarmony藏头诗应用
SkiaSharp 之 WPF 自绘弹跳球(案例版)
C语言文件篇——文件操作
乌克兰总检察长和国家安全局局长被解职
Autojs learning - realize finger action recording
MySQL复合索引示例
Boolean expression satisfiability problem (SAT) and cook Levin theorem (Part 2)
NFT mall /nft blind box / virtual blind box /nft transaction / customizable second opening
Li Kou today's question -565 Array nesting