electron 桌面应用使用心得

270 阅读1分钟

electron开发官方文档

  1. 快速入门, 可以写个简单运行的Demo

  2. 多进程,主进程 + 渲染器进程

    渲染器进程,做到上下文隔离,不能访问Node 功能,要使用 Preload 脚本

  3. 进程间通讯,有单向和双向示例

  4. 渲染器进程做到沙盒化

  5. 性能和安全,官方说明

  6. 简单Demo应用

  7. 开发应用的API

vue 开发,使用vue-cli-plugin-electron-builder插件

使用vue add 会初始化background.js 文件

使用npm安装不会添加

vue add vue-cli-plugin-electron-builder

vue-cli-plugin-electron-builder插件官方网站

  1. 使用预加载文件preload.js

    vue.config.js -> pluginOptions -> electronBuilder 里面设置preload文件位置,插件会自动在dist_electron(运行自动生成文件夹)中生成preload.js

pluginOptions: {
  electronBuilder: {
  preload: 'src/preload.js',
  ...
  }
}

在主进程文件background.js中配置preload

new BrowserWindow({
  fullscreen: true,
  show: false,
  webPreferences: {
  nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
  contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
  preload: path.join(__dirname, 'preload.js')
  }
})
  1. 在预加载文件preload.js中使用 静态资源(mp4, txt, pdf, xlsx...)

    video 标签 src 使用静态资源,

    1)静态资源 放在public 文件夹下

    2)使用__static关键字加载

    // console.log(__static)
      let p = path.join(__static, 'video.mp4')
      const buf = fs.readFileSync(p);
      const uni8Buffer = Uint8Array.from(buf);
      const blob = new Blob([uni8Buffer]);
      const src = window.URL.createObjectURL(blob);
    
    1. 向渲染器进程暴露window
    contextBridge.exposeInMainWorld('work', {
     videoUrl: src
     })
    
    1. 渲染器进程使用
    window.work.videoUrl
    

electron-builder打包配置

查看官网,如下

pluginOptions: {
    electronBuilder: {
	preload: 'src/preload.js',
	builderOptions: {
            productName: "xxx",
            appId: "xxx",
            copyright: "xxx",
            nsis: { 
            //nsis配置参数
		deleteAppDataOnUninstall: true,
		oneClick: false, //可单击打开
		allowToChangeInstallationDirectory: true, //允许用户选择安装位置
		perMachine: true,
		artifactName:"${productName} Setup.${ext}"
            },
            asar:false, // 使用asar 加密
            win: {
		target: [
                    {
                        target: "nsis",
                        arch: [
                            "x64",
                            "ia32"
                        ]
                    }
                ]
            },
            mac: {
		target: 'dmg',
		hardenedRuntime: true,
                gatekeeperAssess: true,
		extendInfo: {
                    NSAppleEventsUsageDescription: 'Let me use Apple Events.',
                    NSCameraUsageDescription: 'Let me use the camera.',
                    NSScreenCaptureDescription: 'Let me take screenshots.',
                }
            }
	// options placed here will be merged with default configuration and passed to electron-builder
	}
    }
}

打包, 经常下载不下来

修改npm 下载源为阿里源