Making the address

The local installation environment is available

  • Install Node: * nodejs.org/en/download…
  • NPM install -g webpack(sudo permission)
  • Windows CNPM:
NPM install - g CNPM - registry=https://registry.npm.taobao.org because the NPM's default warehouse abroad, download slow, domestic taobao make a CNPM, once every 10 minutes synchronization, completely will be enoughCopy the code
  • You can also download it using YARN
    npm install -g yarn
    yarn installCopy the code

Dependency package Installation

  • Enter the project directory
  • Perform CNPM install

Installation problem

  • After CNPM is installed, some packages may be incomplete due to poor network connection. Yarn is recommended
  • You need to install vue-style-loader and vue-template-compiler. Otherwise, vue-Loader will report errors
  • If the electron configuration item (config.js) is true, run NPM run dev, the browser will report an error.Uncaught ReferenceError: require is not defined, the reason can gohereSince the config.electron configuration is enabled, require is browserified instead of the original Node’s native require function, which causes this problem in Browser
  • When using package.json, note that the main configuration item of package.json must point to the electron main thread file, which is app/index.js

Font introduction

For Webpack, there are always problems with importing font files. Sometimes you use file-laoder, url-loader, but there are still some problems with using it. For example, the renderer entry file Components/app. vue wants to import common. SCSS. Common. SCSS will go to @import iconfont. CSS (font style), and the font path of iconfont. In the development environment, I solved the problem by writing the remote address of the font file retrieved from iconfont.cn into build/index.html. In a formal environment, you can introduce the font file code into the app.vue file

Feature list

  • [] The MAC installation package is generated
  • [] Added functions of each module
  • [x] Windows Installation package generation — done
  • [x] Apply automatic updates — done
  • [x] Chinese and English switch — done
  • [x] Global shortcut key binding — done
  • [x] Instant messaging — done
  • [x] Excel table import/export — done
  • [x] Login feature — done
  • [x] Mock. Easy provides data — done

development:

$NPM run dev # express enables the service, which can be accessed via 'http://localhost:port' (hot overload) Create the mainWindow via electron, 'mainwindow.loadurl (http://localhost:port)', load the app's index.html $NPM run app # run 'electron./' to generate the desktop appCopy the code

socket.io:

$NPM run socket Uses express + mongoDB + socket. IO to introduce node-based im modulesCopy the code

For local debugging, simply run NPM run dev => NPM run app. NPM run sock is required to enable im function. Note that im module has not been migrated to the server. You need to use express to set up a service (./socket/), where the database integration is using mongoDB, so you have to install mongoDB and configure the environment variables (for example, if I install the directory D:, my environment variables are configured like this. D: Program Files\MongoDB\Server\ 3.4. bin), then you can use mongod, mongo command, execute the mongod command, there is no default directory for storing documents, so you can create a new folder, Mongod –dbpath D:\mongodb\db, mongo(Models /sechemas), socket. IO, express, mongo(models/sechemas) For these new things, I only have a general understanding, and I’m going to spend some time to study them in depth.

production:

$NPM run build # Generate official file to app/dist directory (eletron app directory)Copy the code

package:

$NPM run package: MAC $NPM run package:win $NPM run package: Linux $NPM run package Generate the program and package it into the './package 'directoryCopy the code

setup:

$NPM run setup generates the installation package (for Windows only). Package the package generated in the previous step with grunt and grunt-electron-installer to './package_dir 'Copy the code

The installation package generation process:

  • npm run build
  • NPM run package:win (currently only supports Window)
  • npm run setup

For the packaging tool, use the electron packager installation command:

rimraf package && electron-packager . TEST --platform=win32 --arch=x64 --overwrite --icon=hosts.ico --out=./package - electron - version = 1.6.11 panyName = TEST - version-string.Com - version - string. ProductName = TEST --ignore=\"(build|client$|static|theme|.gitignore|LICENSE|README.md|.editorconfig|.eslintrc|node_modules|gruntPackage.js on|Gruntfile.js|yarn.lock|socket|package_dir|git_img)\"Copy the code

Parameters:

  • .=> Application directory
  • TEST=> Application name
  • --platform=win32=> Platform to be packaged
  • --overwrite=> Install in overwrite mode
  • --icon=hosts.ico=> Application icon (available on Windows.ico,.pngFor MAC, it can be.icns)
  • --out=./package=> Output directory
  • --electron-version= > electron version
  • --version-string.CompanyName=TEST --version-string.ProductName=TESTTo generate the installation package, the application name isTEST“Rather than the defaultelectron
  • --ignore=XXX=> Ignore the packaged directory

Details can be found here

Grunt and grunt electron- Installer are required to be installed in package.json:

{"version": "1.0.0", // this is necessary in order to automatically update "productName": "my-electron", "description": "My Superb Vue Project For Electron", ...... }Copy the code

The gruntfile.js file is as follows:

Var grunt = require('grunt') // configure grunt. Config. init({PKG: Grunt. File. readJSON('package.json'), 'create-windows-installer': {x64: {authors: 'xiaobinwu <[email protected]>', // projectUrl: ', appDirectory: './package/ test-win32-x64 ', // outputDirectory: './package_dir', Description: 'My Superb Vue Project For Electron', setupIcon: './app/hots.ico', // icon noMsi: Msi}}}) // Load task grunt. LoadNpmTasks ('grunt- electronic-installer ') // Set grunt. RegisterTask ('default', ['create-windows-installer'])Copy the code

The result is something like the one shown abovemy-electronSetup.exe, click “Run” to enter an installation process. There will be a small animation of installation, as shown below:



What we need is an automatic shortcut generated after the installation, which is used hereelectron-squirrel-startupNPM package, and then write to app/index.js in the main thread filestartupEventHandleMethod that triggers some commands of squirrel. Window at installation time and places them in the callback function that creates the body window as follows:

app.on('ready', function(){ ...... startupEventHandle() ...... })... Function startupEventHandle () {if (require(' electronic-squirrel -startup')) {return} Var handleStartupEvent = function () {if (process.platform! == 'win32') { return false } var squirrelCommand = process.argv[1] switch (squirrelCommand) { case '--squirrel-install':  case '--squirrel-updated': install() return true case '--squirrel-uninstall': uninstall() app.quit() return true case '--squirrel-obsolete': Function install () {var cp = require('child_process') var updateDotExe = path.resolve(path.dirname(process.execPath), '.. ', 'update.exe') var target = path.basename(process.execPath) var child = cp.spawn(updateDotExe, ['--createShortcut', target], { detached: true }) child.on('close', Function (code) {app.quit()})} function uninstall () {var cp = require('child_process') var updateDotExe = path.resolve(path.dirname(process.execPath), '.. ', 'update.exe') var target = path.basename(process.execPath) var child = cp.spawn(updateDotExe, ['--removeShortcut', target], { detached: true }) child.on('close', function (code) { app.quit() }) } } if (handleStartupEvent()) { return } }Copy the code

This will generate shortcuts during installation and remove shortcuts during uninstallation. In the process, it is possible to report a similar error when the electron-squirrel-startup module is not found. The node_moudles directory is filtered out, so it needs to be added manually to the generated package. As for some tutorials on the Internet, it is necessary to install VS2015 environment, and declare msbuild program as environment variables, but I think it should be the lack of NPM package, you can also try, I have installed VS2015 locally.

lint:

$NPM run Lint # Lint project (configuration rule:.eslintrc)Copy the code

The above NPM run script command may be a little too many, involving a lot of content, will be explained later in the article! Below is the last wave effect picture:









Electron automatic update

We have also mentioned automatic update before. Here we use the officially provided electron. AutoUpdater module to update. What is frustrating is that there is very little official description of this function. The most important method is autoupdater.setFeedUrl (URL), which puts high versions of files (.exe,.nupkg,RELEASES), I here is stored in the oss, ali and autoUpdater checkForUpdates () to check whether need to update, It raises some of the events in error, check-for-update, update-available, and update-downloaded, and we use the communication between the main process and the rendering process (IPC /remote/webContent). To trigger the update, the code is as follows:

function updateHandle () { ipcMain.on('check-for-update', function (event, arg) { if (process.platform ! == 'win32') {return false} let appName = 'store system' let appIcon = __dirname + '/hots.ico' let message = {error: Checking: 'Checking the update error ', checking:' Checking the update... ', updateAva: 'Download the update successfully ', and updateNotAva:' This is the latest version you are using. Do not update it. ', 'The latest version has been downloaded, '} const OS = require(' OS ') const {dialog} = require('electron' autoUpdater.setFeedURL('http://electron20170815.oss-cn-beijing.aliyuncs.com/electron/') autoUpdater.on('error', function (error) { return dialog.showMessageBox(mainWindow, { type: 'info', icon: appIcon, buttons: ['OK'], title: appName, message: message.error, detail: '\r' + error }) }) .on('checking-for-update', function (e) { return dialog.showMessageBox(mainWindow, { type: 'info', icon: appIcon, buttons: ['OK'], title: appName, message: message.checking }) }) .on('update-available', function (e) { var downloadConfirmation = dialog.showMessageBox(mainWindow, { type: 'info', icon: appIcon, buttons: ['OK'], title: appName, message: message.updateAva }) if (downloadConfirmation === 0) { return } }) .on('update-not-available', function (e) { return dialog.showMessageBox(mainWindow, { type: 'info', icon: appIcon, buttons: ['OK'], title: appName, message: message.updateNotAva }) }) .on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) { var index = dialog.showMessageBox(mainWindow, { type: 'info', icon: appIcon, buttons: [' restart now ', 'restart later '], title: appName, message: message.downloaded, detail: releaseName + '\n\n' + releaseNotes }) if (index === 1) { return } autoUpdater.quitAndInstall() }) autoUpdater.checkForUpdates() }) }Copy the code

If the content is helpful, you can go to Github and give it to star!!!!

Resources: segmentfault.com/a/119000000… Segmentfault.com/a/119000000… Juejin. Cn/post / 684490… Github.com/hua1995116/…


Generated by VuePack.

vuePack Issue