electron经验汇总

2022-04-30 fishedee 前端

0 概述

electron经验汇总

总体而言,整个js生态都缺乏一种严谨的精神,electron也不例外,工具真的好难用

官网在这里

1 快速入门

1.1 安装编译依赖

安装Visual Studio的时候需要注意勾选,使用C++的桌面开发

1.2 环境配置

yarn init

我们最好使用yarn,而不是npm作为包管理器。先用yarn初始化目录

ELECTRON_MIRROR=https://npm.taobao.org/mirrors/electron/
ELECTRON_BUILDER_BINARIES_MIRROR=http://npm.taobao.org/mirrors/electron-builder-binaries/

在本地打开.npmrc文件,并填上以上的配置

{
  "name": "helloworld",
  "version": "1.0.0",
  "authors": "fish",
  "description": "yinghao",
  "main": "main.js",
  "build": {
    "appId": "your.id",
    "mac": {
      "category": "your.app.category.type"
    }
  },
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1",
    "app:dir": "electron-builder --dir",
    "app:dist": "electron-builder"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^18.2.0",
    "electron-builder": "^23.0.3",
    "node-gyp": "^9.0.0"
  }
}

将package.json填写为以上的内容,我们使用electron作为容器,使用electron-builder作为打包工具。在这里,实名吐槽electron-forge真的好垃圾,浪费了很多时间调试环境,打包依然各种报错。

yarn install

安装依赖

1.3 代码

const { app, BrowserWindow } = require('electron')

const createWindow = () => {
    const win = new BrowserWindow({
        show:false,
    })
    win.maximize()
    win.removeMenu()
    win.loadURL("http://www.baidu.com/")
    win.show()
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
  })

app.whenReady().then(() => {
    createWindow()
});

将以上代码保存到main.js文件,因为package.json中指定main入口为main.js文件,所以我们要保存到这个文件中,不能使用其他文件。

1.4 运行

yarn start

会自动打开electron执行,并最大化窗口。

1.5 打包

yarn run app:dist

使用electron-builder发布,并打包文件

dist/win-unpacked/helloworld.exe

会在dist文件夹中输出一个exe文件,该文件要与其所在的目录放在一起才能正常执行,win-unpacked的文件夹大概有160MB。

dist/hello world Setup 1.0.0.exe

dist文件夹默认生成nsis安装器,双击会自动安装到Users目录的一个应用,在桌面和开始菜单都有一个图标。我们也可以指定为portable(绿色版)安装,这个也比较方便。

相关文章