1. 首页
  2. 技术分享

electron入门

一、基础环境配置

# 克隆示例项目的仓库
$ git clone https://github.com/electron/electron-quick-start

# 进入这个仓库
$ cd electron-quick-start

# 安装依赖并运行
$ npm install && npm start

# 安装开发辅助工具
$ npm install nodemon --save-dev

修改package.json文件中的start方式为:

  "scripts": {
    "start": "nodemon --watch main.js --exec \"electron .\""
  },

二、electron进程

electron入门

  1. 主进程-Main process
    • 可以使用和系统对接的 Electron AP|-创建菜单,上传文件等等
    • 创建渲染进程-Renderer Process
    • 全面支持 node.js
    • 只有一个,作为整个程序的入口点
  2. 渲染进程- Renderer Process
    • 可以有多个,每个对应一个窗口
    • 每个都是一个单独的进程
    • 全面支持node.js和 DOM AP
    • 可以使用一部分 Electron提供的APl
  3. 进程间的通讯
    • Electron使用IPC(interprocess communication)在进程之间进行通讯(和Chromium完全一致)
      electron入门

三、入门示例

  1. 创建窗口:修改main.js文件如下,执行npm start 即可启动
const {app, BrowserWindow } = require('electron')
app.on('ready', () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  mainWindow.loadFile('index.html') //main.js同级目录html文件
  const secondWindow = new BrowserWindow({
    width: 400,
    height: 300,
    webPreferences: {
      nodeIntegration: true
    },
    parent:mainWindow
  })
  secondWindow.loadFile('second.html')//main.js同级目录html文件
})
  1. 进程将通讯

main.js

const {app, BrowserWindow,Menu,ipcMain } = require('electron')
app.on('ready', () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  Menu.setApplicationMenu(null) //取消头部菜单
  mainWindow.loadFile('index.html')
  ipcMain.on('message',(event,arg)=>{
   console.log(arg)
  //  event.sender.send('mainMessage',"hello from main")
   mainWindow.send('mainMessage',"hello from main")
  })
})

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'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <p id="message"></p>
    <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 require other files to run in this process -->
    <script src="./renderer.js"></script>
    <!-- <script>
      require('./renderer.js')
    </script> -->
  </body>
</html>

renderer.js

const { ipcRenderer } = require('electron')
window.addEventListener('DOMContentLoaded',()=>{
    ipcRenderer.send('message','hello from renderer')
    ipcRenderer.on('mainMessage',(event,arg)=>{
       document.getElementById('message').innerHTML = arg
    })
})

四、electron 持久化解决方案

本地文件持久化

$ npm install electron-store --save

代码:

const Store = require('electron-store');
const store = new Store();//不设置文件名称,持久化数据将保存到config.json文件中
//如果需要加密存储 就用下面的
//const store = new Store({encryptionKey: '加密值'});
store.set('unicorn', '这是需要存储的内容');
console.log(store.get('unicorn')); //=> '这是需要存储的内容'
// Use dot-notation to access nested properties
store.set('foo.bar', true);
console.log(store.get('foo')); //=> {bar: true}
store.delete('unicorn');
console.log(store.get('unicorn'));  //=> undefined

五、应用的打包与分发

打包方式:

  • 手动打包(繁琐)
  • Electron packager
  • Electron builder

以Electron builder为例:

npm install electron-builder --save-dev

package.json 配置参考:package.json

{
  "name": "zulip",
  "productName": "Zulip",
  "version": "2.5.0-beta",
  "main": "./app/main",
  "description": "Zulip Desktop App",
  "license": "Apache-2.0",
  "copyright": "Kandra Labs, Inc.",
  "author": {
    "name": "Kandra Labs, Inc.",
    "email": "support@zulipchat.com"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/zulip/zulip-electron.git"
  },
  "bugs": {
    "url": "https://github.com/zulip/zulip-electron/issues"
  },
  "engines": {
    "node": ">=6.0.0"
  },
  "scripts": {
    "start": "electron app --disable-http-cache --no-electron-connect",
    "reinstall": "node ./tools/reinstall-node-modules.js",
    "postinstall": "electron-builder install-app-deps",
    "lint-css": "stylelint app/renderer/css/*.css",
    "lint-html": "./node_modules/.bin/htmlhint \"app/renderer/*.html\" ",
    "lint-js": "xo",
    "test": "npm run lint-html && npm run lint-css && npm run lint-js",
    "test-e2e": "gulp test-e2e",
    "dev": "gulp dev & nodemon --watch app/main --watch app/renderer --exec 'npm test' -e html,css,js",
    "pack": "electron-builder --dir",
    "dist": "electron-builder",
    "mas": "electron-builder --mac mas",
    "travis": "cd ./scripts && ./travis-build-test.sh",
    "build-locales": "node tools/locale-helper"
  },
  "pre-commit": [
    "test"
  ],
  "build": {
    "appId": "org.zulip.zulip-electron",
    "asar": true,
    "files": [
      "**/*",
      "!docs${/*}",
      "!node_modules/@paulcbetts/cld/deps/cld${/*}"
    ],
    "copyright": "©2019 Kandra Labs, Inc.",
    "mac": {
      "category": "public.app-category.productivity",
      "artifactName": "${productName}-${version}-${arch}.${ext}"
    },
    "linux": {
      "category": "Chat;GNOME;GTK;Network;InstantMessaging",
      "packageCategory": "GNOME;GTK;Network;InstantMessaging",
      "description": "Zulip Desktop Client for Linux",
      "target": [
        "deb",
        "zip",
        "AppImage",
        "snap"
      ],
      "maintainer": "Akash Nimare <akash@zulipchat.com>",
      "artifactName": "${productName}-${version}-${arch}.${ext}"
    },
    "deb": {
      "synopsis": "Zulip Desktop App",
      "afterInstall": "./scripts/debian-add-repo.sh",
      "afterRemove": "./scripts/debian-uninstaller.sh"
    },
    "snap": {
      "synopsis": "Zulip Desktop App"
    },
    "dmg": {
      "background": "build/appdmg.png",
      "icon": "build/icon.icns",
      "iconSize": 100,
      "contents": [
        {
          "x": 380,
          "y": 280,
          "type": "link",
          "path": "/Applications"
        },
        {
          "x": 110,
          "y": 280,
          "type": "file"
        }
      ],
      "window": {
        "width": 500,
        "height": 500
      }
    },
    "win": {
      "target": [
        {
          "target": "nsis-web",
          "arch": [
            "x64",
            "ia32"
          ]
        }
      ],
      "icon": "build/icon.ico",
      "artifactName": "${productName}-Web-Setup-${version}.${ext}",
      "publisherName": "Kandra Labs, Inc."
    },
    "nsis": {
      "allowToChangeInstallationDirectory": true,
      "oneClick": false,
      "perMachine": false
    }
  },
  "keywords": [
    "Zulip",
    "Group Chat app",
    "electron-app",
    "electron",
    "Desktop app",
    "InstantMessaging"
  ],
  "devDependencies": {
    "assert": "1.4.1",
    "cp-file": "5.0.0",
    "devtron": "1.4.0",
    "electron": "3.0.10",
    "electron-builder": "20.40.2",
    "electron-connect": "0.6.2",
    "electron-debug": "1.4.0",
    "google-translate-api": "2.3.0",
    "gulp": "4.0.0",
    "gulp-tape": "0.0.9",
    "htmlhint": "0.11.0",
    "is-ci": "1.0.10",
    "nodemon": "1.14.11",
    "pre-commit": "1.2.2",
    "spectron": "5.0.0",
    "stylelint": "9.10.1",
    "tap-colorize": "1.2.0",
    "tape": "4.8.0",
    "xo": "0.18.2"
  },
  "xo": {
    "parserOptions": {
      "sourceType": "script",
      "ecmaFeatures": {
        "globalReturn": true
      }
    },
    "esnext": true,
    "overrides": [
      {
        "files": "app*/**/*.js",
        "rules": {
          "max-lines": [
            "warn",
            {
              "max": 700,
              "skipBlankLines": true,
              "skipComments": true
            }
          ],
          "no-warning-comments": 0,
          "object-curly-spacing": 0,
          "capitalized-comments": 0,
          "no-else-return": 0,
          "no-path-concat": 0,
          "no-alert": 0,
          "guard-for-in": 0,
          "prefer-promise-reject-errors": 0,
          "import/no-unresolved": 0,
          "import/no-extraneous-dependencies": 0,
          "no-prototype-builtins": 0
        }
      }
    ],
    "ignore": [
      "tests/*.js",
      "tools/locale-helper/*.js"
    ],
    "envs": [
      "node",
      "browser",
      "mocha"
    ]
  }
}
npm run dist

六、完整示例

基于electron固件的office工具箱已开源,实现了基于excel和word模板快速生成word及word批量转换pdf的功能,开源地址:electron-office-tools

原创文章,作者:小童子,如若转载,请注明出处:https://www.caobinrg.com/547.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注

联系我们

邮件:caobinrg@163.com