开发 Electron + Vite 遇到的坑

334 阅读1分钟
1、使用 require 引入导致的错误

实现一个解压文件的功能的时候使用了 compressing

const compressing = require('compressing')

compressing.zip
      .uncompress(downFilePath, decompressionPath)
      .then(() => {
        e.sender.send('extractFileProgress', { msg: '解压完成!' })
      })
      .catch(() => {
        e.sender.send('extractFileProgress', { err: '解压失败,请手动安装!' })
      })

dev环境是没问题的,打包之后报各种错,提示缺少各种module

A JavaScript error occurred in the main process
Uncaught Exception: Error: Cannot find module 'mkdirp'

发现是 compressing 库中 package.json 的一些依赖,最后使用 import 导入之后就解决了

2、从 electron 暴露方法
import { contextBridge, ipcRenderer } from 'electron'

const electronExpose = {
  downloadFile: (params: DownloadProgressParams) => ipcRenderer.invoke('downloadFile', params),
  downloadProgress: (callback: (event: Electron.IpcRendererEvent, resp: DownloadProgressResponse) => void) =>
    ipcRenderer.on('downloadProgress', callback),
}

contextBridge.exposeInMainWorld('electronExpose', electronExpose)

export type ElectronExpose = typeof electronExpose

起初想直接通过回调函数将进度返回

downloadFile: (params: DownloadProgressParams,cb:DownloadProgressResponse) => ipcRenderer.invoke('downloadFile', params, cb)

但是报错了,最后查到原因,在暴露的时候不能传递 function,需要使用 ipcRenderer.on('downloadProgress', callback),在页面进行监听就行了

electronExpose.downloadProgress((_e, { err, progress, isDone }) => {
    ...
})