electron

electron配置

# 1. 1.全局安装 asar 依赖

pnpm add -g asar

注意,必须使用 cmd

  1. 进入 release/win-unpacked/resources 文件夹
  2. 打开终端执行 asar extract app.asar ./ 命令即可查看打包后的文件目录。
  3. 查看解压 asar e .\app.asar ./app

# 2. 2.sqlite3 镜像

better_sqlite3_binary_host=https://registry.npmmirror.com/-/binary/better-sqlite3
better_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/better-sqlite3
better-sqlite3_binary_host=https://registry.npmmirror.com/-/binary/better-sqlite3
better-sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/better-sqlite3

# 3. 当前终端设置临时环境变量,也可以在系统环境变量设置

set ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
set NSIS_MIRROR=https://npmmirror.com/mirrors/nsis/
set NSIS_RESOURCES_MIRROR=https://npmmirror.com/mirrors/nsis-resources/
set WIN_CODE_SIGN_MIRROR=https://npmmirror.com/mirrors/win-code-sign/

# 4. 打包 betterSqlite3 打包兼容 32 位操作系统

https://blog.csdn.net/zhaihmj/article/details/139630124
1. 进入工作目录
npx electron-rebuild -f -w better-sqlite3 --arch=ia32  # 32位安装包
npx electron-rebuild -f -w better-sqlite3 --arch=x64  # 64位安装包

# 5. 全局设置打包平台 ia32 、 x64

node-gyp configure --arch=ia32
  • 安装完 python3.x 后,出现 import gyp # noqa: E402 和 'binding.gyp' 不需要 npm install -g node-gyp
  pip install setuptools
  • 手动编译 better-sqlite3 使用预编译版本(Electron 项目推荐) better-sqlite3 在安装时会尝试下载预编译的二进制文件,如果找不到匹配版本才会本地编译。你可以手动指定 Electron 版本和平台架构来避免编译:
npm install better-sqlite3 --build-from-source --runtime=electron --target=31.0.0 --dist-url=https://electronjs.org/headers

请将 --target=31.0.0 替换为你实际使用的 Electron 版本。

  • Ubuntu 安装 Python、C++ 编译工具和其他依赖
sudo apt-get update
sudo apt-get install -y python3 python3-pip build-essential libssl-dev

# 6. 问题

  1. app.isPackaged 在 win7 的 32 位操作系统识别有问题,解决方案:使用 !is.dev 或者环境变量 import.meta.env.MODE === 'production'
  2. process.cwd() 在 window 上安装有目录错误的问题,避免使用

# 7. 解决控制台中文乱码

终端执行以下命令: chcp 65001

# 8. 查看端口占用

netstat -aon|findstr "3001"

杀死进程命令:taskkill /PID 53176 -T -F (其中-T 是包括了子进程,-F 是强制) taskkill /PID 15712 -T -F

# 9. linux 下打包问题

  • 安装 ar 工具
# ar 是一个标准的工具,通常在 binutils 软件包中包含。你可以使用以下命令来安装 binutils,从而获取 ar 工具。

sudo apt-get update
sudo apt-get install binutils

  • 检查依赖 确保你已经安装了 fpm 依赖工具(如 dpkg, rpm, ar 等),因为 fpm 使用这些工具来构建不同类型的包文件。特别是 Debian 系列的 .deb 包依赖于 dpkg 和 ar
sudo apt-get install dpkg-dev
  • 其他非依赖(可选)
sudo apt-get install libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 xdg-utils libatspi2.0-0 libuuid1 libsecret-1-0
  • 你可以修改 electron-builder 配置文件,或者在命令行中手动添加该标志:(可选)
--deb-no-default-config-files

"build": {
  "linux": {
    "target": {
      "target": "deb",
      "arch": [
        "x64"
      ]
    },
    "deb": {
      "fpm": [
        "--deb-no-default-config-files"
      ]
    }
  }
}

# 10. 文件设置权限

sudo chmod -R 755 /home/zy/Desktop/hyt-exam-cliten/
如果文件所有者不属于你当前的用户,可以使用 chown 命令更改文件所有者。
sudo chown -R $(whoami) /home/zy/Desktop/hyt-exam-cliten/

# 11. 安装文件

sudo apt install ./your-package-name.deb

# 12. 卸载文件

sudo apt remove package-name // package 的 name

# 13. 设置代理

export http_proxy=http://10.5.4.120:10809
export https_proxy=http://10.5.4.120:10809

# 14. 麒麟操作系统关闭防火墙

sudo apt-get install firwalld firewall-config
systemctl stop firewalld

# 15. 统信 uos vscode 运行 watchers 报错

sudo sysctl fs.inotify.max_user_watches=524288
[来源](https://zhuanlan.zhihu.com/p/599156184)

# 16. 主窗口全屏创建置顶的子窗口,会短暂显示桌面的问题

childWindow?.webContents.on('did-finish-load', () => {
  childWindow?.setAlwaysOnTop(true) //置顶逻辑一定要放到这里
  // childWindow?.webContents.send(IpcMessageType.sendRenderConnect, data)  // 发送渲染进程内容至少要要延迟40ms才能行,因为渲染进程还没启动好
  const rendererProcessId = winInfo.webContents.getProcessId()
  console.log('窗口渲染进程的 ID:', rendererProcessId)
})

# 17. 直接下载文件到本地

const ipc = require('electron').ipcMain

ipc.on('save-dialog', (event, src) => {
  /* dialog.showSaveDialog({
    title: '导出',
    filters: [
        {name: 'All', extensions: ['*']},
    ]
  }, res => {
     //直接下载url
      mainWindow.webContents.downloadURL(res)
  }) */
  dialog.showErrorBox('报错标题', '报错内容')
  // mainWindow.webContents.downloadURL(src.imageSrc)
})

# 18. 打开网页(浏览器方式)

const { shell } = require('electron')
shell.openExternal(url)

# 19. 加载渲染进程 renderer 下指定路由

const winURL = is.dev
  ? `${process.env['ELECTRON_RENDERER_URL']}`
  : join(__dirname, '../renderer/index.html')
const pageUrl = mainWindows.webContents.getURL() //获取当前页面url
pageUrl = 'info' //指定路由;如http://localhost:5172/#/info  ;根路径为 '/';路由模式必须是hash模式,history模式需要做特殊处理,不建议使用
if (is.dev) {
  mainWindows.loadURL(winURL, { hash: pageUrl })
} else {
  mainWindows.loadFile(winURL, { hash: pageUrl })
}

# 20. 加载静态资源作为渲染进程的资源,且指定路由

访问 http://localhost:3800/my 页面;dist 为静态资源目录,index.html 为渲染进程的入口文件;

// xx.js
mainWindows.loadURL('http://localhost:3800/dist/#/my')
// router.js
const express = require('express')
const app = express()
const path = require('path')
import mimeTypes from 'mime-types'

router.get('/dist', async (req, res, next) => {
  try {
    const concatUrl = await getProjectInfoUrl()
    const staticPath = path.join(concatUrl, 'index.html')
    const reqUrl = req.url
    res.sendFile(staticPath)
  } catch (error) {
    res.send('404')
  }
})

router.get('/dist/static/* || /dist/assets/*', async (req, res, next) => {
  if (req.url.startsWith('/static/') || req.url.startsWith('/assets/')) {
    const extname: string = path.extname(req.url)
    const mime: string = mimeTypes.lookup(extname)
    const staticPath = await getProjectInfoUrl()
    const lastPath = join(staticPath, req.url)
    readFile(lastPath, (err, data) => {
      if (err) {
        res.status(404).send('assets资源未找到')
      } else {
        res.setHeader('Content-Type', mime)
        res.send(data)
      }
    })
  } else {
    next()
  }
})

# 21. 拖拽限制

# 21.1. 限制拖拽窗口的 x、y 轴位置

/**
 * 窗口移动计算,让其不能超出屏幕边界
 * @param winInfo - child window, including methods to get and set its position.
 * @param width - The width of the screen.
 * @param height - The height of the screen.
 * @param childWidth - The width of the child window.
 * @param slider - Threshold value to determine the adjustment limits (default is 100).
 *
 * repositioning it within bounds if necessary.
 */

export function getWindowWidthAndHeight(params): void {
  const {
    winInfo, //子窗口信息
    width, //屏幕宽度
    height, //屏幕高度
    childWidth, //子窗口宽度
    slider = 100 //临界值
  } = params
  const [positonsX, positonsY] = winInfo.getPosition()

  let newX = positonsX || 0
  let newY = positonsY || 0
  /**
   * x轴左方
   * x轴点位置最小为屏幕宽度 - 临界值
   */
  let crisisLX = childWidth - Math.abs(newX)
  if (newX < 0 && crisisLX < slider) {
    newX = -childWidth + slider
  }

  /**
   * x轴右方
   * x轴点位置最小为屏幕宽度 - 临界值
   */
  const crisisRX = newX + slider
  if (crisisRX >= width) {
    newX = width - slider
  }

  /**
   *  y轴下方
   * y轴点位置最小为屏幕高度 - 临界值
   */
  const crisisY = newY + slider
  if (crisisY >= height) {
    newY = height - slider
  }

  /**
   * y轴上方
   * y轴点位置最大为0
   */
  if (newY <= 0) {
    newY = 0
  }

  if (newX !== positonsX || newY !== positonsY) {
    console.log('位置', newX === positonsX, '位置', newY === positonsY)
    // 设置窗口位置
    winInfo?.setBounds({ x: newX, y: newY })
  }
}

# 21.2. 使用

openCalculate() {
  const windowInfo = new WindowInfo()
  const primaryDisplay = screen.getPrimaryDisplay()
  const { width, height } = primaryDisplay.workAreaSize
  const childWidth = 320
  const childHeight = 540

  calacWin = windowInfo.createWindows({
    route: '/calculator',
    parentId: 1,
    minimizable: true,
    width: childWidth,
    height: childHeight,
    resizable: false,
    title: '计算器',
    modal: false,
    titleBarStyle: 'default',
    skipTaskbar: true // 不显示在任务栏
  })

  if (calacWin) {
    calacWin?.webContents.on('did-finish-load', () => {
      calacWin?.setAlwaysOnTop(true)
    })

    calacWin?.on('close', () => {
      calacWin = null
    })
    calacWin?.on(
      'move',
      throttle(() => {
        getWindowWidthAndHeight({
          winInfo: childrenWin,
          width,
          height,
          childWidth
        })
      }, 50)
    )
  }
}

# 22. electron-builder 安装后的升级文件路径

User\AppData\Local\electronName-updater  #electronName 是package.json的name字段

# 23. 打包后在 windows 运行静默安装

powershell 命令行必须是终端管理员模式,否则会提示权限不足。 正常使用 cmd 行运行如下命令:

安装程序.exe /S
上次更新: