This paper reference: zhuanlan.zhihu.com/p/75764907 the outline of this article

This article teaches you how to use Electron9 and VUE-CLI3 step by step to build desktop applications while retaining the habit of developing Web applications using VUE.

This article does not cover the development of Electron and VUE tutorial, only for the purpose of realizing the combination of the two. For in-depth study of Electron and VUE, please visit the official website:

Electron: electronjs.org/

vue: cn.vuejs.org/

vue-cli: cli.vuejs.org/zh/

sass: www.sass.hk

Before you study this article, you should be familiar with the following skills:

HTML, CSS, JavaScript vue2. X sass

Electron basis

※ Note: “+” at the beginning of each line in the code area of this article means new, “-” means deleted, and “M” means modified; “… “in code Represents omission.

Here’s what you can learn from this tutorial:

directory

1 Creating a Project

1.1 Use CNPM to speed up download

1.2 Why not use SimulatedGREG/ electronic-vue

1.3 Installing or Upgrading VUE-CLI3

1.4 Creating a VUE project

1.5 Automatically Installing the Electron sensor

1.6 Manually Installing the Electron Sensor

1.7 Compile and Start the APP

2 Configuration Items

2.1 Configuring the ESLint Code Format checker

2.2 Configuring the Prettier plug-in Formatting the configuration file

2.3 configuration vue

3. Basic project Settings

3.1 Introduction to main process and rendering process

3.2 APP window size

3.3 Removing cross-domain Restrictions

3.4 Cancel the top menu bar

3.5 Setting the APP Window Icon

3.6 Setting the title bar name of the APP Window

4 build the final product

4.1 Setting ICONS of the APP and installation package

4.2 packaging APP

4.3 Possible problems when packing

4.4 Packaged more configuration

5 Configuration and Questions

5.1 Using the Node module in the renderer process

5.2 Cancel the outer border

5.3 Manually Installing vue-devTools

5.4 Registering Shortcut Keys Open devTools

5.5 Setting the Drag area in a Window

5.6 Background-js code analysis

5.7 The renderer calls the main process module

6 Migrate the VUE project to electron-vue-demo

1 Creating a Project

1.1 Use CNPM to speed up download

Domestic direct use of NPM official mirror is very slow, here recommended to use Taobao NPM mirror.

Use taobao’s customized CNPM (gzip compression support) command line tool instead of the default NPM

npm install -g cnpm --registry=https://registry.npm.taobao.org
Copy the code

This allows you to install the module using the CNPM command

cnpm install [name]
Copy the code

After setting it, all NPM install will be downloaded from Taobao server by default. Check whether the setting is successful by using NPM config list. After success, the value of metrics-registry will be changed to taobao server address

npm config set registry  https://registry.npm.taobao.org
Copy the code

Switch back to the default address for download, so that when running NPM install [name], you will not download from Taobao image

npm config set registry https://registry.npmjs.org/
Copy the code

1.2 Why not use SimulatedGREG/ electronic-vue

SimulatedGREG/ electric-Vue has not been updated for a long time, and the resulting engineering structure is not vuE-CLI3. So give it up

1.3 Installing or Upgrading VUE-CLI3

As OF this writing, MY VUE-CLI3 version is 3.12.1

Run this command to check the VUe-CLI version

vue --version
Copy the code

If the version is earlier than 3, uninstall it first

cnpm uninstall vue-cli -g
Copy the code

If you do not specify NPM install -g@vue /cli, you will download the latest VUE-cli4. The configuration in it is different from that in 3, so far it has not been studied. If readers already use vuE-CLI4, skip it.

NPM install - g @ vue/[email protected]Copy the code

Vue-cli official link: cli.vuejs.org/zh/

1.4 Creating a VUE project

Find a directory you like and execute the following command to create a vue project:

(Name the project as electron- VUe-demo here)

vue create electron-vue-demo
Copy the code

The following options appear (skip this section if you are familiar with this step) :

Vue CLI v3.12.1? Please pick a preset: (Use arrow keys) > default (babel, eslint) Manually select featuresCopy the code

Select Manually select Features (custom installation).

? Please pick a preset: Manually select features
? Check the features needed for your project:
 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 (*) Router
 (*) Vuex
>(*) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing      
Copy the code
? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) n 
Copy the code

Select CSS preprocessing module, here we use “Sass/SCSS (with Node-sass)”

> Sass/SCSS (with node-sass)
Copy the code

Select the configuration of the ESLint code format checker and select ESLint + Standard Config for Standard configuration.

❯ ESLint + Standard config 
Copy the code

Line on save means that when saving code, a formatting check is performed.

Lint and fix on commit means that formatting is automatically corrected at Git commit time.

Select only “Lint on Save” here.

>(*) Lint on save
Copy the code

Where do I put configuration files like Babel, postCSS, esLint?

In dedicated Config files indicates an independent file

In package.json means to put it In package.json

Select “In package.json” here.

 In package.json 
Copy the code

Do you reserve these Settings for future projects? Choose “N”.

Then wait patiently for the project installation to complete.

? Save this as a preset for future projects? (y/N) n  
Copy the code

1.5 Automatically Installing the Electron sensor

※ Note: This process may require scientific Internet, due to the direct download from foreign image is slow, may need to wait a very long time. If you’re not super confident about your Internet speed, skip this section and go to section 1.6 to install it manually.

Go to the project root directory and execute:

vue add electron-builder
Copy the code

Automatic installation depends on this command line plug-in: Vue CLI Plugin Electron Builder, do not install yourself. All you need to do is open a terminal in the directory of the application you created using VUe-CLI 3 or 4 and run Vue add electron- Builder.

IO /vue-cli-plu… Vue CLI Plugin Electron Builder nklayman.github.

During installation, you might get stuck at this step (I didn’t experience this) :

node ./download-chromedriver.js
Copy the code

That’s okay. Let’s just force it out. Run the vue Add electron- Builder one more time and you’re good to go.

Next comes the configuration options:

? Choose Electron Version (Use arrow keys)
  ^7.0.0
  ^8.0.0
> ^9.0.0
Copy the code

Select the Electron version. Select the “^ 9.0.0”.

Then wait patiently for the installation to complete. If an error interrupts, repeat this step.

After installation, background.js is automatically generated in the SRC directory and package.json is modified.

※ Note: Due to network reasons, if there is an interruption failure, re-installation may be completed quickly, but in fact Electron may not be fully installed. You are advised to delete node_modules/ in the root directory of the project and run CNPM install to reinstall all dependent packages from the domestic image.

1.6 Manually Installing the Electron Sensor

※ Note: If you have already completed the operations described in Section 1.5, please skip this section.

Modify package.json to add the following 8 lines:

."scripts": {
    "serve": "vue-cli-service serve"."build": "vue-cli-service build"."lint": "vue-cli-service lint",
+    "electron:build": "vue-cli-service electron:build",
+   "electron:serve": "vue-cli-service electron:serve",
+    "postinstall": "electron-builder install-app-deps",
+    "postuninstall": "electron-builder install-app-deps"
  },
+  "main": "background.js"."dependencies": {
    "core-js": "^ 2.6.5." "."vue": "^ 2.6.10"."vue-router": "^ 3.0.3." "."vuex": "^ 3.0.1." "
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^ 3.12.0"."@vue/cli-plugin-eslint": "^ 3.12.0"."@vue/cli-service": "^ 3.12.0"."@vue/eslint-config-standard": "^ 4.0.0"."babel-eslint": "^ 10.0.1." ",
 +  "electron": "^ 9.0.0",
 +  "electron-devtools-installer": "^ 3.1.0"."eslint": "^ 5.16.0"."eslint-plugin-vue": "^ 5.0.0"."node-sass": "^ 4.12.0"."sass-loader": "^ 8.0.0." ",
 + "vue-cli-plugin-electron-builder": 5 "" ^ 2.0.0 - rc.."vue-template-compiler": "^ 2.6.10"},...Copy the code

New SRC/background. Js

Create background.js under SRC and copy the following code:

'use strict'

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
constisDevelopment = process.env.NODE_ENV ! = ='production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app'.privileges: { secure: true.standard: true}}])async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if(! process.env.IS_TEST) win.webContents.openDevTools() }else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')}}// Quit when all windows are closed.
app.on('window-all-closed'.() = > {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if(process.platform ! = ='darwin') {
    app.quit()
  }
})

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()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready'.async() = > {if(isDevelopment && ! process.env.IS_TEST) {// Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message'.(data) = > {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM'.() = > {
      app.quit()
    })
  }
}

Copy the code

The above code was installed in an automated manner in Section 1.5.

Installing dependency packages

Execute in the project root directory to install all dependencies:

cnpm install
Copy the code

Error: post install Error, please remove node_modules before retry! It can be ignored and does not affect subsequent use. (I have not come across this.)

1.7 Compile and Start the APP

Run the following command to start compiling the APP and start the development environment APP:

npm run electron:serve
Copy the code

The initial startup may take a long time, and the following information is displayed:

Failed to fetch extension, trying 4 more times
Failed to fetch extension, trying 3 more times
Failed to fetch extension, trying 2 more times
Failed to fetch extension, trying 1 more times
Failed to fetch extension, trying 0 more times
Vue Devtools failed to install: Error: net::ERR_CONNECTION_TIMED_OUT
Copy the code

This is because the vuejs DevTools plug-in is installed on the request. Need scientific Internet to install successfully. It doesn’t matter if you can’t access the Internet scientifically, wait patiently for 5 failed requests and then automatically skip.

Once compiled successfully, the APP for the development environment will appear.

Since it cannot be downloaded, and I will try to download it again every time I save the file for hot update, I will annotate the corresponding code here, and then download vue-devTools manually from the official website of VUE and install it. For details, please refer to 5.3

Import installExtension, {VUEJS_DEVTOOLS} from "electronic-devtools-installer "; // Import installExtension, {VUEJS_DEVTOOLS} from" electronic-devtools-installer "; . // Delete the corresponding method belowCopy the code

2 Configuration Items

2.1 Configuring the ESLint Code Format checker

ESlint can efficiently check code formatting so that all engineers working on a project can maintain a uniform code style. The detection accuracy can even be accurate to whether there is one more space or one less space. The unification of the code format is of great help to improve the efficiency of the collaborative development of the team, especially for the engineers who are obsessed with code cleanliness.

Create.eslintrc.js in the project root directory

Notice the “before the file name. .eslintrc.js overwrites the package.json configuration when eslintConfig is also configured in package.json. You can delete the eslintConfig configuration in package.json

Please paste the following code:

module.exports = {
  root: true.env: {
    node: true,},extends: ['plugin:vue/essential'.'@vue/standard'].rules: {
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'.// Do not detect semicolons at the end of statements
    semi: ['off'.'always'].// Enforces an indentation of 2 Spaces
    indent: ['error'.2].// Turn off whitespace detection between function names and parentheses
    'space-before-function-paren': 0.// Ignore Spaces in braces
    'object-curly-spacing': 0.// Trailing commas are allowed (but not required) when the last element or attribute is on a different line from the closing parenthesis] or}; When in the same line, do not use trailing commas.
    'comma-dangle': ['error'.'only-multiline'].Camel spelling is required
    camelcase: [
      'error',
      {
        properties: 'never'.// Do not check the attribute name
        ignoreDestructuring: true.// Do not check destruct identifiers},],},parserOptions: {
    parser: 'babel-eslint',}}Copy the code

This is my usual.eslintrc.js configuration. If you have more configuration requirements, see cn.eslint.org/docs/rules

The default formatted configuration file is.editorConfig. The configuration is as follows:

[*.{js, JSX,ts, TSX,vue}] indent_style = space trim_trailing_whitespace = true insert_final_newline = trueCopy the code

Editorconfig role:

The formatting plug-in prettier preferes the configuration file in the project, but it cannot be configured without a semicolon in. Editorconfig, so I use the. Prettierrc configuration file to do the same as the. Editorconfig file

2.2 Configuring the Prettier plug-in Formatting the configuration file

The formatting plug-in I use is Prettier. If you don’t use prettier, use the official documentation to configure it yourself. Delete. Editorconfig, create.prettierrc.js

. Prettierrc. Js:

module.exports = {
  trailingComma: "es5".// 'es5': trailing comma valid in ES5 (object, array, etc.) 'all': trailing comma possible (function argument)
  tabWidth: 2.// The number of Spaces taken by each TAB character
  semi: false.// Whether to add semicolons at the end of each line
  singleQuote: true.// Whether to use single quotation marks
};
Copy the code

Here’s the.prettierrc.js configuration I usually use. IO /docs/en/con if you have more configuration requirements, see prettier. IO /docs/en/con…

.editorconfig,.prettierrc.js for IDE (vscode I use) automatic formatting code.eslintrc.js for ESlint detection

Eslint can be turned off if you really don’t like it:

// vue.config.js
lintOnSave: false
Copy the code

2.3 configuration vue

Create vue.config.js in the project root directory and paste the following code:

const path = require('path');

function resolve (dir) {
  return path.join(__dirname, dir);
}

module.exports = {
  publicPath: '/'.devServer: {
    // can be overwritten by process.env.HOST
    host: '0.0.0.0'.port: 8080
  },
  chainWebpack: config= > {
    config.resolve.alias
      .set(The '@', resolve('src'))
      .set('src', resolve('src'))
      .set('common', resolve('src/common'))
      .set('components', resolve('src/components')); }};Copy the code

DevServer is used to set up the services of the development environment, which means that the Web service is started locally on port 8080.

ChainWebpack We give the project directory an “alias”. In the code, we can directly use the “alias” to access the resource, saving the trouble of entering the full relative path each time.

※ Note: ◉ can be used directly in js code, such as: @/common/js/xxx.js is equivalent to SRC /common/js/xxx.js common/js/xxx.js ◉ To use an alias in the CSS or HTML, add ~ before the alias, for example: @import “~common/stylus/font.styl”;

3. Basic project Settings

3.1 Introduction to main process and rendering process

Before we begin, it is important to take a brief look at Electron’s application architecture.

The main process

The Electron process running the package.json main script (background.js) is called the main process. The script running in the main process presents the user interface by creating a Web page. A Electron application always has one and only one main process.

Rendering process

Since Electron uses Chromium to present Web pages, Chromium’s multi-process architecture is also used. Each Web page in Electron runs in its own rendering process.

In normal browsers, Web pages usually run in a sandbox environment and are not allowed to touch native resources. However, Electron users can perform some low-level interactions with the operating system on the page with the support of the Node.js API.

Relationship between the main process and the renderer process

The main process creates the page using the BrowserWindow instance. Each BrowserWindow instance runs the page in its own rendering process. When an instance of BrowserWindow is destroyed, the rendering process is terminated.

The main process manages all the Web pages and their corresponding renderers. Each renderer process is independent and only cares about the Web page it is running on.

Specific please see the official document: electronjs.org/docs/tutori…

3.2 APP window size

Change background. Js:

const win = new BrowserWindow({
M    width: 1200,
M    height: 620.webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
    }
  })
Copy the code

Set up the full screen

Here’s the code. I’m using the setFullScreen method because my project needs full screen.

  const win = new BrowserWindow({
    width: 1200.height: 620.webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
 +    fullscreen: true,
 +    skipTaskbar: false,
 +    fullscreenable: true,
 +    simpleFullscreen: true, +}// This method can not block the taskbar when it is in full screen
 +    // win.maximize()	
 +    // This method can block the lower taskbar
 +    win.setFullScreen(true)});Copy the code

The width and height Settings are invalid when the screen is full

3.3 Removing cross-domain Restrictions

Change background. Js:

const win = new BrowserWindow({
    width: 1200.height: 620.webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
+     webSecurity: false,}})Copy the code

3.4 Cancel the top menu bar

  // Remove the window top menu
  win.setMenu(null);
Copy the code

3.5 Setting APP window icon (I use Win10 system, not effective, effective after packaging)

Prepare the Windows and macOS maps.

Windows: app.ico Minimum size: 256×256 macOS: app. PNG or app.icns Minimum size: 512×512 (used in section 4.1)

Put the icon file in the public/ directory. The project structure is as follows:

| | - / dist_electron (slightly) - / public | - app. Icns < - this tutorial is not used temporarily icns | - app. Ico | - app. PNG | - the favicon. Ico | - index. | - HTML/SRC (abbreviated)Copy the code

You can change favicon.ico as well, but it won’t work on the desktop APP. This will only be used if you generate a pure Web project later.

Modify background.js to apply the APP window icon:

. +const path = require('path')...const win = new BrowserWindow({
    width: 1200.height: 620,
+   icon: path.join(__static, 'app.ico'), // Taskbar ICONS and taskbar preview ICONS are placed in the public directory
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false,}}); .Copy the code

${__static} corresponds to the public directory

3.6 Setting the title bar name of the APP Window

Modify the electron-vue-demo in public/index.html (my project has removed the outer border, so I can’t see the title)

4 build the final product

Here we have integrated the electron Builder tool. The official documentation can be found at: github.com/electron-us…

4.1 Setting the APP name and icon

Modify vue.config.js and add the following code:

  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true.// The renderer can use the Node module
      builderOptions: {
        win: {
          icon: "./public/app.ico"
        },
        mac: {
          icon: "./public/app.png"
        },
        productName: "AppDemo"}}}Copy the code

This is configured with the packaged application icon and the name of the application installed on the desktop

4.2 packaging APP

To build the project, run the following command:

npm run electron:build
Copy the code

Finally, build the product in the dist_electron directory.

4.3 Possible problems when packing

Due to network problems, the contents of the two files in the figure may not be downloaded. You can download them from Github according to the corresponding file path in the command line, and then put them in the folder

Here is a download link for the package file. It may not be the same as your version. Use the download link in the command line tool

Link: pan.baidu.com/s/15V7eUTSl…

Extraction code: GL03

The inside of the folder looks like this:

There are two versions because I created the project with electron-vue earlier, and that dependency version is lower

4.4 Packaged more configuration

Here further do some configuration, so that the output package can customize the installation path, etc.

Reference: www.electron.build/configurati…

The vue. Config. Js:

.// Import package.json to get project information in the file
  const PACKAGE = require('./package.json')
  let config = {
      productName: PACKAGE.name,
      version: PACKAGE.version,
  }
  ...
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true.// The renderer can use the Node module
      builderOptions: {
        asar: false.productName: `${config.productName}`.// Project name, which is also the prefix of the generated EXE file
        appId: 'com.electron.template'.// Application id
        copyright: 'Copyright © template'.// Application copyright line
        directories: {
          output: 'dist_electron'.// Package the output directory relative to the project root path
        },
        win: {
          legalTrademarks: 'Copyright © template'.// Trademark registration
          publisherName: 'electron'.// Publisher name, identical to the name in the code signing certificate
          requestedExecutionLevel: 'highestAvailable'.// The security level of the application request execution.
          target: [{target: 'nsis'.// Target package type
              arch: ['ia32'].// Is a 32-BIT version of the BAI architecture on X86},].// The installation package name when nSIS is not configured. This configuration item will be overwritten by NSIS
          // artifactName: `${config.productName}.exe`,  
          icon: './public/app.ico'.// The icon path, installation package and free installer will all be applied
        },
        mac: {
          identity: 'com.electron.templat'.target: ['dmg'].// artifactName: `${config.productName}.dmg`,
          icon: './public/app.png',},dmg: {
          title: `${config.productName}`.// artifactName: `${config.productName}.dmg`,
          icon: './public/app.png',},nsis: {
          // Create a one-click installer or auxiliary installer
          oneClick: false.// Whether to allow users to change the installation directory.
          allowToChangeInstallationDirectory: true.// Whether to display the Setup mode setup page for secondary setup (select per computer or per user). Or whether it is always installed by all users (per machine)
          perMachine: true.// Allow application for promotion. If false, the user will have to restart the setup program with the enhanced permissions
          allowElevation: true.${productName} Setup ${version}.${ext}, ${productName} corresponds to name in productName or package.json. ${version} corresponds to version in package.json
          artifactName: `${config.productName}- Installation package -v${config.version}.exe`.// Whether to run the installed application after completion. For secondary installers, the corresponding check box is removed
          runAfterFinish: true.// The name used for all shortcuts. The default is the application name, the value of productName. If productName is not set, it defaults to name in package.json. If name is not set either, an error will be reported
          shortcutName: `${config.productName}`,},},},},Copy the code

5 Configuration and Questions

5.1 Using the Node module in the renderer process

// vue.config.js
module.exports = {
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true}}}Copy the code

The value of process.env.electron_node_integration is set to true in vue. Config. js, corresponding to background.js

nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
Copy the code

5.2 Cancel the outer border

  const win = new BrowserWindow({
    width: 1200.height: 620.webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false.// eslint-disable-next-line no-undef
      icon: path.join(__static, 'icon.png'),
      
    },
 +   frame: false});Copy the code

More reference: www.bookstack.cn/read/electr…

5.3 Manually Installing vue-devTools

The automatic download failed because of network problems. Here, download vue-devtools manually and place it in the dist_electron folder because __dirname is based on it.

Vue-devtools can be downloaded at github.com/vuejs/vue-d…

In the session. The defaultSession. LoadExtension method loading plug-ins, pay attention to judgment in the development environment to the load

app.on("ready".async() = > {// Only load vue-devTools in the development environment
  if(isDevelopment && ! process.env.IS_TEST) {// Install Vue Devtools
    loadVueDevTools()
  }
  createWindow();
});

// Load vue developer tools
function loadVueDevTools() {
  session.defaultSession
    .loadExtension(path.join(__dirname, "./devTools/vue-devtools"))
    .then(res= > {
      console.log("Vue Devtools loaded successfully");
    })
    .catch(err= > {
      console.error("Vue Devtools failed to install:", err.toString());
    });
}
Copy the code

5.4 Registering Shortcut Keys Open devTools

Once set up, CommandOrControl+Shift+ I is available to toggle developer mode on

In Windows, press Ctrl+Shift+ I to switch to devTools

On macOS, press Commond+Shift+ I to toggle devTools

Since F12 is a system reserve shortcut, F12 is not used here

app.on("ready".async() = > {// Only load vue-devTools in the development environment
  if(isDevelopment && ! process.env.IS_TEST) {// Install Vue Devtools
    loadVueDevTools()
    registerToggleDevTools()
  }
  createWindow();
});

// Register shortcut key toggle to open developer tools
function registerToggleDevTools() {
   globalShortcut.register("CommandOrControl+Shift+i".function() {
    BrowserWindow.getFocusedWindow().webContents.toggleDevTools();
  });
}
Copy the code

5.5 Setting the Drag area in a Window

After setting this property on the specified element, click to drag the window

-webkit-app-region: drag;
Copy the code

Use -webkit-app-region: no-drag within dragable regions to exclude some of them. Note that currently only rectangular shapes are supported

The text choose

In a frameless window, drag behavior may conflict with selection text. For example, when you drag the title bar, you might accidentally select the text on the title bar. To prevent this operation, you need to disable text selection in the available area, as follows:

.titlebar {
  -webkit-user-select: none;
  -webkit-app-region: drag;
}
Copy the code

5.6 Background-js code analysis

5.6.1 variable

  • process.env.NODE_ENV

    The development environment is Development

    The production environment is Production

  • process.env.ELECTRON_NODE_INTEGRATION

    This corresponds to the nodeIntegration property in vue.config.js

  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true.// The renderer can use the Node module
      builderOptions: {
        win: {
          icon: "./public/app.ico"
        },
        mac: {
          icon: "./public/app.png"
        },
        productName: "AppDemo"}}}Copy the code
  • process.env.WEBPACK_DEV_SERVER_URL

    The url corresponding to the local startup service is http://localhost:8080

  • __static

    The absolute path to the corresponding project’s public directory

5.6.2 method

  • createProtocol(“app”)

    From import {createProtocol} from “vue-cli-plugin-electron-builder/lib”; As follows:

export default scheme => {
  protocol.registerBufferProtocol(
    scheme,
    (request, respond) = > {
      let pathName = new URL(request.url).pathname
      pathName = decodeURI(pathName) // Needed in case URL contains spaces

      readFile(path.join(__dirname, pathName), (error, data) = > {
        if (error) {
          console.error(`Failed to read ${pathName} on ${scheme} protocol`, error)
        }
        const extension = path.extname(pathName).toLowerCase()
        let mimeType = ' '

        if (extension === '.js') {
          mimeType = 'text/javascript'
        } else if (extension === '.html') {
          mimeType = 'text/html'
        } else if (extension === '.css') {
          mimeType = 'text/css'
        } else if (extension === '.svg' || extension === '.svgz') {
          mimeType = 'image/svg+xml'
        } else if (extension === '.json') {
          mimeType = 'application/json'
        }

        respond({ mimeType, data })
      })
    },
    error= > {
      if (error) {
        console.error(`Failed to register ${scheme} protocol`, error)
      }
    }
  )
}
Copy the code

For protocal modules, not yet understood ~

5.7 The renderer calls the main process module

5.7.1 Remote Module Description

The Remote module provides an easy path for interprocess communication (IPC) between the renderer process (web page) and the host process. In Electron, guI-related modules (dialog, Menu, etc.) only exist in the main process, not in the rendering process. In order to use them from the renderer, the IPC module is used to send interprocess messages to the main process. Using the remote module, you can invoke methods on the main process object without explicitly sending interprocess messages.

The remote module is disabled by default and needs to be enabled in BrowserWindow – of the main process by setting enableRemoteModule to true

const win = new BrowserWindow({
    width: 1200.height: 620.webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false.// eslint-disable-next-line no-undef
      icon: path.join(__static, 'icon.png'),
 +    enableRemoteModule: true,},frame: false});Copy the code

5.7.2 Usage Example

Example: Creating a browser window from the renderer process

const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({ width: 800.height: 600 })
win.loadURL('https://github.com')
Copy the code

6 Migrate the VUE project to electron-vue-demo

My vUE project was created by vue-cli3. I migrated the entire SRC folder into the SRC folder of electron vue-demo because my project relies on Element-UI and Axios.

 cnpm i -S element-ui axios
Copy the code

Then run: NPM run electron:serve has run up, mei Zi ~!