preface

Recently, I was assigned a job of desktop application. I haven’t worked on desktop application for a long time, so I decided to review my knowledge and sort out the process. Enter the text!

The body of the

1. Initialize the Node project and generate the package.json file

Use the command NPM initCopy the code
Json file {"name": "my-electron-app", "version": "1.0.0", "description": "Hello World!" , "main": "main.js", "author": "Jane Doe", "license": "MIT" }Copy the code

2, installation,electronTo rely on the project, use any of the following commands:

npm install --save-dev electron
cnpm install --save-dev electron
yarn add electron --dev
Copy the code

3. Package. json configuration content is as follows:

{" name ":" electron ", "version" : "1.0.0", "description" : ""," main ":". The main js ", "scripts" : {" test ", "echo" Error: no test specified" && exit 1", "start": "electron ." }, "author": "", "license": "ISC", "devDependencies": {"electron": "^17.1.2"}}Copy the code

4. Create front-end projects or introduce front-end projects. The project directory is the following structure:

--main.js
--preload.js
--index.html
--package.json
Copy the code

5. Refer to the official website to create the main.js entry file and configure the following contents:

Const {app, BrowserWindow, const {app, BrowserWindow, Menu} = require('electron') const path = require('path') function createWindow () {// Hide Menu bar Menu.setApplicationMenu(null) // create BrowserWindow const win = new BrowserWindow({//width: 800, // window width, pixels. The default is 800 //height: 600, // window height in pixels. The default is 600 icon: './logo.ico', // set the icon show: false in the upper left corner of the window, // whether the window is displayed when it is created. Default is true webPreferences: {nodeIntegration: true, // Whether node is fully supported. Default is true preload: path.join(__dirname, 'preload.js') // Preloads a specified script before other scripts run on the interface. }}) // The following two lines match the show in new BrowserWindow above: False, Maximize Windows when opened win.maximize() win.show() // and load index.html win.loadfile ('index.html')} // for your application Electron calls this method when initialization is complete and it is ready to create the browser window. // Part of the API will not be available until the ready event is triggered. App.whenready ().then(createWindow) // Exit app.on('window-all-closed', () => {// on macOS, unless the user exits with Cmd + Q, // Otherwise, most apps and their menu bar remain active. if (process.platform ! == 'Darwin ') {app.quit()}}) app.on('activate', () => {// On macOS, when the Dock icon is clicked and no other window opens, // usually a new window is created in the application. if (BrowserWindow.getAllWindows().length === 0) { createWindow() } })Copy the code

Create preload.js. All Node.js apis can be used to configure the following during preloading:

// preload.js // All node.js apis can be used during preloading. // It has the same sandbox as Chrome extensions. 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]) } })Copy the code

Create an index.html file that matches win.loadfile (‘index.html’) in main.js

8. Run the command NPM start to quickly open your Web application and check whether the application configuration is correct.

9. Install the package dependency using the following two methods: electron- Packager and electron- Builder

A, the electron – packager

(1) Use the electron packager package and install the electron packager dependency. Install either of the following:

npm install --save-dev electron-packager
cnpm install --save-dev electron-packager
yarn add electron --dev
Copy the code

② After the installation is successful, configure the package.json file as follows:

"scripts": { "start": "electron .", "packager": "Electron packager. 'app' --platform=win32 --arch=x64 --out=./build --electron version 9.0.2 --app-version 1.0.0 --overwrite --icon=./logo.ico" },Copy the code

Packager parameters:

-arch: x84 or X64, -outapp location can be replaced with the name of your exe after packing. -electron -version: The version of electron must be specified. In this case, set it to 1.6.2. You can view the version number of electron installation in package.json -icon icon addressCopy the code

③ Run the NPM run packager command to see the build file in the root directory of the project. Run the EXE file to see the packaged project.

Second, the electron – builder

① Use the electron builder package, install the electron Builder dependency, one of the following installation can be:

npm install  electron-builder --save-dev
cnpm install  electron-builder --save-dev
yarn add electron-builder --dev
Copy the code

② After the installation is successful, configure the package.json file as follows:

{ "scripts": { "test": "echo "Error: no test specified" && exit 1", "start": "electron .", "build": "Construct" "build": {"productName":" XXXX ", // project name "appId": Directories "electron. App ", // Package directories" directories": {"output": "build"}, // Output folder "copyright":" XXXX ", // copyright information "nsis": {// nSIS related configuration, effective when packaged as nSIS "oneClick": false, // Whether to install "allowElevation": true, // Allow requests for promotion, if false, then the user must restart the installer with the promoted permission. "AllowToChangeInstallationDirectory" : true, / / allowed to change the installation directory "installerIcon" : "./build/ ICONS /aaa.ico", // Install icon "uninstallerIcon": "./build/ ICONS /bbb.ico", // uninstall icon "installerHeaderIcon": "./build/ ICONS /aaa.ico", // Install header icon "createDesktopShortcut": true, // create desktop icon "createStartMenuShortcut": True, // Create the start menu icon "shortcutName": "XXXX ", // create the icon name "include": "Build/script/installer. NSH", / / contains custom nsis script}, / / release to making the publish: {provider: 'lot', ': Git repository owner: 'XXXX ', // Owner token:' XXXXXXXXXXXXXXX ', // gitToken releaseType: 'release', publishAutoUpdate: True // Publish automatic updates (GH_TOKEN is required). By default, true} / / configure Windows environment "win" : {" icon ":" build/ICONS/aims. Ico ", "target" : [" nsis ", "zip"]}, / / configure MAC environment "MAC" : {" target ":" get ", "zip"]}, / / configure Linux environment "Linux" : {" icon ": "Build/ICONS"}}} / / from: https://segmentfault.com/a/1190000016695922?utm_source=tag-newestCopy the code

③ Run the NPM run build command to see the build file in the root directory of the project. Run the EXE file to see the packaged project.

A simple desktop application is generated.

conclusion

This article has only briefly covered the installation process of Electron and successfully packaged it as a desktop application, but there is much more that has not been shown, and I will share more details in the future.