electron-builder采坑

2,408 阅读3分钟

背景:用vue-cli3搭建了一个前端项目,由于甲方爸爸想要一个桌面的应用,在此基础上使用了electron-builder,MAC开发

1.vue add electron-builder

(选择版本,最新即可)

package.json

{
  "name": "hello-web",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "electron:build": "vue-cli-service electron:build --win",
    "electron:serve": "vue-cli-service electron:serve",
    "postinstall": "electron-builder install-app-deps",
    "postuninstall": "electron-builder install-app-deps",
    "upload": "node upload.js"
  },
  "main": "background.js",
  "dependencies": {
    "axios": "^0.21.0",
    "core-js": "^3.6.5",
    "file-saver": "^2.0.2",
    "js-cookie": "^2.2.1",
    "jszip": "^3.5.0",
    "moment": "^2.29.1",
    "view-design": "^4.3.2",
    "vue": "^2.6.11",
    "vue-router": "^3.2.0",
    "vuex": "^3.4.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-standard": "^5.1.2",
    "babel-eslint": "^10.1.0",
    "echarts": "^4.9.0",
    "electron": "^9.0.0",
    "electron-devtools-installer": "^3.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "eslint-plugin-vue": "^6.2.2",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "scp2": "^0.5.0",
    "vue-cli-plugin-electron-builder": "~2.0.0-rc.5",
    "vue-particles": "^1.0.9",
    "vue-template-compiler": "^2.6.11"
  },
  "__npminstall_done": false
}

background.js

'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'
const isDevelopment = 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,
    fullscreen: true,
    // frame: false,
    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('线上地址 eg: http//:xxxx')
  }
}

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

vue.config.js

pluginOptions: {
    electronBuilder: {
      builderOptions: {
        appId: 'cn.psvmc',
        productName: 'hephaestus',
        icon: './app.ico',
        files: ['**/*', 'static/*'],
        asar: true,
        mac: {
          icon: './Icon.icns',
          target: ['zip', 'dmg']
        },
        win: {
          icon: './app3.ico',
          target: ['zip', 'nsis']
        },
        nsis: {
          oneClick: false, // 是否一键安装
          allowElevation: true, // 允许请求提升。 如果为false,则用户必须使用提升的权限重新启动安装程序
          allowToChangeInstallationDirectory: true, // 允许修改安装目录
          installerIcon: './app3.ico', // 安装图标
          uninstallerIcon: './app3.ico', // 卸载图标
          installerHeaderIcon: './app3.ico', // 安装时头部图标
          createDesktopShortcut: true, // 创建桌面图标
          createStartMenuShortcut: true, // 创建开始菜单图标
          // license: './LICENSE.txt',
          shortcutName: 'hephaestus' // 图标名称
        }
      }
    }
  }

安装遇到的坑待补充。。。。

2.使用electron-builder打包时下载electron失败解决方案

electron-builder 在打包时会检测cache中是否有electron 包,如果没有的话会从github上拉去,在国内网络环境中拉取的过程大概率会失败,所以你可以自己去下载一个包放到cache目录里

各个平台的目录地址

Linux: $XDG_CACHE_HOME or ~/.cache/electron/
MacOS: ~/Library/Caches/electron/
Windows: %LOCALAPPDATA%/electron/Cache or ~/AppData/Local/electron/Cache/
➜  clipboard git:(master) ✗ npm run dist

> clipboard@1.0.0 dist /Users/xx/workspace/electron/clipboard
> electron-builder --mac --x64

  • electron-builder  version=22.3.2 os=18.7.0
  • loaded configuration  file=package.json ("build" field)
  • writing effective config  file=dist/builder-effective-config.yaml
  • packaging       platform=darwin arch=x64 electron=8.0.0 appOutDir=dist/mac
  • downloading     url=https://github.com/electron/electron/releases/download/v8.0.0/electron-v8.0.0-darwin-x64.zip size=66 MB parts=8

可以单独下载这个包 github.com/electron/el… 放到~/Library/Caches/electron/ 目录下

3.打包会遇到缓存问题

macOS

打包所需依赖缓存位置:

$ ~/Library/Caches/electron
$ ~/Library/Caches/electron-builder

程序缓存位置:

$ ~/Library/Application Support/Caches

Linux:

$ ~/.cache/electron-builder

windows:

$ %LOCALAPPDATA%\electron\cache
$ %LOCALAPPDATA%\electron-builder\cache

4.为 Electron windows/mac 应用配置图标

electron-builder 中设置应用icon要求:

windows支持icon格式:png、ico

mac支持icon格式:png、icns

macOS:Icon size should be at least 512x512.

windows: Icon size should be at least 256x256

windows ico图标生成方式: www.ico51.cn/

mac icns 图标生成方式:命令行方式生成

准备一个png图片,假设名字为 pic.png

使用以下命令行创建一个临时目录存放不同大小的图片

$ mkdir tmp.iconset

把原图片转为不同大小的图片,并放入上面的临时目录

全部拷贝到命令行回车执行,执行结束之后去tmp.iconset查看十张图片是否生成好

sips -z 16 16     pic.png --out tmp.iconset/icon_16x16.png
sips -z 32 32     pic.png --out tmp.iconset/icon_16x16@2x.png
sips -z 32 32     pic.png --out tmp.iconset/icon_32x32.png
sips -z 64 64     pic.png --out tmp.iconset/icon_32x32@2x.png
sips -z 128 128   pic.png --out tmp.iconset/icon_128x128.png
sips -z 256 256   pic.png --out tmp.iconset/icon_128x128@2x.png
sips -z 256 256   pic.png --out tmp.iconset/icon_256x256.png
sips -z 512 512   pic.png --out tmp.iconset/icon_256x256@2x.png
sips -z 512 512   pic.png --out tmp.iconset/icon_512x512.png
sips -z 1024 1024   pic.png --out tmp.iconset/icon_512x512@2x.png

通过iconutil生成icns文件:

$ iconutil -c icns tmp.iconset -o Icon.icns