What is the electron

When it comes to cross-platform desktop applications, the first thing you might think is that QT is very high performance because it is relatively low level, but it is expensive to develop in C++ for the front end

Then is NW a few years ago or very active after all nail nail wechat Web development tools are based on its development, but all its Windows share a Node.js environment so the coupling line is relatively high, behind the basic half dead.

Electron is a cross-platform desktop GUI application development framework based on Web front-end technology that is easier to use than QT, more comprehensive than NW, and has a more active community. Here’s a comparison of the three: Electron is a framework for building desktop applications using JavaScript, HTML and CSS, as stated in the official documentation. The embeddedChromium 和 Node.jsElectron allows you to keep a code base of JavaScript code and create cross-platform applications for macOS and Linux running on Windows — no local development experience required.www.electronjs.org/

Install and run:

1. Install the electron file as normal. Because the file is relatively large, you are advised to use Taobao image or YARN.

2. Create main.js in the outermost directory as the main process of the program.

3. Then add “main”: “main.js” to package.json;

4. Add the startup command “electron-start”: “electron.” Normally, start the project first and then run the startup command. But for convenience I can set up a command to do this: since I’m building my project with UMI, I’m listening directly on port 8000

"electron-dev":  "concurrently \" wait-on http://localhost:8000 && electron .\" \"npm start\" ",
Copy the code

Now that I know the command to start, I need to write the main process-related logic in main.js:

What can the main process do

Ps: Just list a few

Listen for electron initialization to set the main window parameter BrowserWindow

1. Create a browser window

const { app, BrowserWindow} = require('electron'); Function createWindow() {// Create a BrowserWindow mainWindow = new BrowserWindow({width: 1150, height: 750, minWidth: 1); // Create a BrowserWindow mainWindow = new BrowserWindow({width: 1150, height: 750, minWidth: 1) 1150, minHeight: 750, frame: true, resizable: false, Plugins: true, nodeIntegration: true, // Nodejs webSecurity: false, enableRemoteModule: }}) const ipc = require('electron').ipcmain; // mainwindow.destroy () // app.quit(); // mainwindow.destroy () // app.quit(); / / app. The quit () / / mainWindow. Hide ()}) mainWindow. WebContents. OpenDevTools () if (isDevelopment) {/ / / / open the developer tools, load application LoadURL ('http://localhost:8000/')} else {// Official version const pathName = path.join(__dirname, 'dist/index.html') mainwindow.loadFile (pathName)} // The following event is triggered when the window is closed. (e) => {// Retrieve BrowserWindow object mainWindow = null; })}Copy the code

2. After electron is initialized, call a function to create a window

app.whenReady().then(createWindow)
//or
app.on('ready', createWindow)
Copy the code
Custom tray
const { Tray,Menu } = require('electron'); Let trayMenuTemplate = [{label: 'BIM ', click: function () {mainwindow.show ();}}, {label: 'exit ', click: Function () {app.quit(); app.quit(); function () {app.quit(); // system trayIcon directory let trayIcon = path.join(__dirname, ''); AppTray = new Tray(path.join(trayIcon, 'icon.ico')); // appTray = new Tray(path.join(trayIcon, 'icon.ico')); Const contextMenu = menu.buildFromTemplate (trayMenuTemplate); // App. // Set the hover prompt for the tray icon apptray.setToolTip (' title '); appTray.setContextMenu(contextMenu); On ('click',function(){mainwindow.show (); })Copy the code
Custom popovers because they are Windows, the browser’s native popovers can be captured and customized
const { dialog } = require('electron'); Function showMessage(text) {const options = {type: 'info', title: 'prompt ', message: text, } dialog.showMessageBox(options) };Copy the code
Communicates with the renderer process

1. The renderer sends a message to the main process

You can use ipcrenderer. send to send custom instruction messages

import { ipcRenderer } from 'electron'; ipcRenderer.send('aaa'); //aaa is a custom directiveCopy the code

2. The main process listens for messages sent by the renderer process

Specific instructions sent by the renderer can be listened for via ipc.on

Then you can through the mainWindow. WebContents. Send or “e.r eply back message to rendering process Similar to chat

const ipc = require('electron').ipcMain; ipc.on('big', (e)=>{mainwindow.webcontents.s end or ('tobig') // e.ply returns a message to the render process ('tobig',true)})Copy the code

3. Renderer receives

It’s similar to the main process but the main process is ipcMain and the renderer is ipcRenderer

import { ipcRenderer } from 'electron'
ipcRenderer.on('aaa',()=>{

})
Copy the code

4. Or use remote directly in the renderer, which can call methods on the main process object

import { remote } from 'electron';
const BrowserWindow = remote.BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://www.baidu.com');
Copy the code

But one thing to mention here is that the es6 introduction electron is an error # fs.existsSync is not a function

At present, I have two reasonable solutions:

1. Create a JS file in index.html global import to mount the object on the windowCopy the code
    renderer.js:   global.electron = require('electron');
    index.html:
    <script>
      window.electron = require('electron');
    </script>
Copy the code
< span style = "max-width: 100%; clear: both; clear: bothCopy the code
chainWebpack (config,{webpack}) {
    config
      .target('electron-renderer') 
},
Copy the code

packaging

Electron – packager and electron – builder
If you do not use the "history" mode, you will not find the CSS and JS files. If you do not use the "devDependencies" mode, you will not find the project path Because the electron configuration.npmrc file will be redownloaded using the electron packager note file permissions and files that need to be ignored 2. Disadvantages of using electron packager: No update is supported. Few configuration items are installed. Advantages: No complex operations are required, and configuration items are basicCopy the code
"packager-build": "Electron packager. app --out BIMapp --arch=x64 --icon./public/bim -- Out Packed executable file, where to put -- ARCH operating system -- icon Application icon -- Overwrite Whether to overwrite original files ignore files to be ignoredCopy the code

Exe is the packaged application project code all in reources

3. Pack the project code before using the electron Builder packageCopy the code
 "builder": "cross-env npm run build && cross-env node electron-build/index.js",
Copy the code

Electron – build/index. Js:

const defaultConfig = { ia32: true, config: { 'appId': appId, 'productName': 'copyright': 'LZG ',// copyright information 'asar': False, / / do you need a visa 'compression will: normal', / / compression level store | normal | maximum 'extraMetadata' : {/ / packaging cover package json 'name' : Directories 'output': 'app/music.test}/v${_package.version}'}, 'publish': {' provider ':', / / server providers, can also be a lot harder 'url' : '/ / server address},' files' : [' main. Js', 'main / * * / *', 'the from: 'dist/index', 'to' : 'dist', 'filter' : [' * * / * ', '! *. The map]], 'DMG: {/ / ios' sign' : False, / / signature 'icon' : ', / / / / 'background' icon: 'electron - build/resource/background. JPG' / / background},... MacSignConfig, 'MAC ': {'identity': '', // iD 'hardenedRuntime': true, 'gatekeeperAssess': false,' Entitlements ': 'electron-build/entitlements.mac.plist', 'entitlementsInherit': 'electron-build/entitlements.mac.plist', 'target': DMG / / / 'dir' ' ', 'zip'], 'icon' : ', / / ICONS 'category' : 'io.bell.Edu cation', 'extendInfo: {' CFBundleURLTypes' : 'codesprite', 'NSMicrophoneUsageDescription' : 'music need your microphone access', 'NSCameraUsageDescription' : 'music need your video head permissions'}},' win ': {/ / win system' artifactName ':' name _v ${version}. ${ext} ', / / name 'icon' : ', / / ICONS 'target' : [ { 'target': 'nsis', 'arch': [ 'x64' ] } ] // ... WinSignConfig}, 'nsis': {// nSIS related configuration, effective when packaged as nSIS ' 'language': '0x0804', 'oneClick': If false, / / a key installation 'allowToChangeInstallationDirectory' : true, / / allowed to modify the installation directory 'allowElevation' : True,// allows requests for promotions, if false, then the user must restart setup with promoted privileges. 'createDesktopShortcut': true,// Create desktop icon 'createStartMenuShortcut': true,// Create start menu icon 'installerIcon': ',// Install icon 'deleteAppDataOnUninstall': true// Uninstall cleans up user data. } } } builder .build(defaultConfig) .then(results => { }) .catch((err) => { console.log(err) })Copy the code
The above is my common packaging configuration information and some of the main instructions have been notedCopy the code

Here it is: You have finished packing for the Electron project