vue3 + electron12+dll 开发客户端配置详解

2,111 阅读6分钟

当前使用的版本为 @vue/cli4 创建的 vue3.0 + typescript + electron 12 版本创建,其他版本暂未测试。网上资料良莠不齐,因此花费时间依次试验,达到一个目前最优解。

修改仓库源

由于electron版本的未知性,可能存在serve可用而build之后打开白屏的情况,因此需要谨慎对待。最好在版本可用的情况下commit一个版本,方便代码回滚,如果谁有更好的资料希望共享。

  • 在开始配置前,可以将yarn和npm的rc文件稍作修改,使用命令或者文件直接修改.npmrc或者.yarnrc,这两个全局配置文件一般在C:\user\你的当前账户这个文件夹下,或者在当前项目下新建文件命令rc文件以局部更改配置。

因为electron下载会因为网络问题而失败,因此修改为淘宝源,华为源亦可。

npm set config registry http://registry.npm.taobao.org/
npm set config chromedriver_cdnurl http://registry.npm.taobao.org/chromedriver
npm set config electron_mirror http://registry.npm.taobao.org/electron/
npm set config electron_builder_binaries_mirror http://registry.npm.taobao.org/electron-builder-binaries/

安装过程使用 vue create <your projectname> 自选为vue3版本,内容创建后进入项目目录,追加 vue electron-builder 配置electron,版本选择当前12版本。

启动

在package.json中已经装配好对应的启动命令,

  • 使用npm run electron:serve 开启开发
  • npm run electron:build 编译打包生产

更换vue-devtools

项目工程下 src/background.ts 为electron的启动目录,开发环境下会出现启动等待时间较长的以下情况

Launching Electron...
Failed to fetch extension, trying 4 more times
Failed to fetch extension, trying 3 more times
Failed to fetch extension, trying 2 more times
Failed to fetch extension, trying 1 more times

是因为项目需要联网谷歌商店下载并加载vue-devtools失败导致。

尝试了很多办法加载tools均失效,因此暂行手段:去掉tools。代码找到,去掉 installExtension 即可

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

之前试了很多办法,不可用。后来再仔细对照以下,发现了一些问题。

vue3的版本和vue2版本的vue-devtools已然不同,所以vue2的dev-tools并不能给vue3使用,因此,需要下载vue3对应的开发工具。vue2版本最新为5.x,而vue3的版本则为6.x beta版本。可以通过crx4chrome下载此版本的插件。将下载好的crx解压出来,然后拷贝到工程根目录下 采用session加载的形式,将原来 await installExtension(VUEJS_DEVTOOLS)的部分替换为

import {session} from 'electron'

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
    const vue_devtools = 'ljjemllljcmogpfapbkkighbhhppjdbg-6.0.0-beta-13-Crx4Chrome.com'
    await session.defaultSession.loadExtension(path.resolve(vue_devtools))
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})

启动项目后,即可以查看 vue 的扩展。 对于

(node:5904) ExtensionLoadWarning: Warnings loading extension at E:\scan\vue3_electron\ljjemllljcmogpfapbkkighbhhppjdbg-6.0.0-beta-13-Crx4Chrome.com:
  Unrecognized manifest key 'browser_action'.
  Unrecognized manifest key 'update_url'.
  Permission 'contextMenus' is unknown or URL pattern is malformed.
  Cannot load extension with file or directory name _metadata. Filenames starting with "_" are reserved for use by the system.
(Use `electron --trace-warnings ...` to show where the warning was created)

可以不予理会。如果不想看到烦人的提示可以到tools的manifest.json中删掉提示对应的内容

注意事项

  1. <script setup> 语法不可以使用

    当使用script-setup作为模块时,在serve阶段可以正常使用,但是在build之后组件未加载,页面呈现空白,且不报错,原因未知

  2. 使用 electron-edge-js 加载 c# 开发的 dll 文件,配置过程略微繁琐,花费2天时间寻求解答,但是均未果,以下是解决办法,需要对症下药

    c++和c#开发的dll使用不同的加载器,c++使用ffi-napi。

    • 使用edge需要同时增加三处配置

    1. 当什么都没有配置时,将会发生 Uncaught (in promise) Error: Cannot find module '...\node_modules\electron\dist\resources\electron.asar\renderer\native\win32\x64\14.16.0\edge_nativeclr' 此时需要在vue.config.js文件增加,如果没有配置文件,则需要在package.json同级创建。
    module.exports = {
        pluginOptions: {
            electronBuilder: {
                externals: ['electron-edge-js']
            }
        }
    }
    
    1. 当配置未开启时,将不能使用 __dirname __filename等nodejs内置变量 Uncaught (in promise) ReferenceError: __dirname is not defined 首先需要配置 new BrowserWindow
    {      
        // 如果使用到nodejs的api,则打包时需要将此设置为true
        nodeIntegration: true,
        // 同时,需要设置此项为false
        // 未设置时报 Uncaught ReferenceError: require is not defined
        contextIsolation: false  
    }
    
    1. 以上配置完成后会报 Uncaught (in promise) TypeError: fs.existsSync is not a function 此时需要继续增加 vue.config.js 的配置项
    module.exports = {
        pluginOptions: {
            electronBuilder: {
                externals: ['electron-edge-js'],
                // 此处同样需要开启,将会在编译阶段将引用关系写入
                nodeIntegration: true, 
            }
        }
    }
    
    1. 如果单独配置此项,但是并没有开启 new BrowserWindownodeIntegration: true ,则会发生 Uncaught ReferenceError: require is not defined

    2. 此外,对于dll放置的文件夹,一般在项目根目录创resources用于存放资源,并且项目打包过程中会不会直接打包资源目录,所以需要增加资源配置,以防止出错。对于文件的引用,在开发环境下,为当前所看到的结构,当编译打包后,为安装目录下resources目录,所以生产和开发的引用文件存在一定区别,可以实验后再看文件引用

     module.exports = {
         pluginOptions: {
             electronBuilder: {
                 externals: ['electron-edge-js'],
                 // 此处同样需要开启,将会在编译阶段将引用关系写入
                 nodeIntegration: true, 
                 builderOptions:{
                     extraResources: {
                         // 拷贝静态文件到指定位置,否则会提示文件找不到
                         from: 'resources/',
                         to: './'
                     },
                 }
             }
         }
     }
    

    提供文件获取目录方法,可以直接获取不同操作系统下app的resource目录,如果是window即 process.platform==='win32'

    const path = require('path')
    export function getAppResourcePath (filePath:string) {
        if (process.platform === 'darwin' || process.platform === 'linux') {
            if (process.env.NODE_ENV === 'development') {
                return path.resolve('resources/' + filePath)
            } else {
                return path.join(__dirname, '..') + filePath
            }
        } else {
            return path.resolve('resources/' + filePath)
        }
    }
    

    使用setup语法时,需使用require('electron-edge-js')引入,不可以使用import,否则会报 Syntax Error: TypeError: Cannot read property 'content' of null 而非 setup语法,则可以直接import

无边框窗口

系统本身是带有框架的,如果需要自定义框架,可以使用frameless 设置,如果需要使用自定义组件(比如 div.custom-frame-title)拖拽操作窗口时,需要给对应的元素增加样式:

 .custom-frame-title {
   -webkit-user-select: none; // 此项防止与文本选择冲突
   -webkit-app-region: drag; // 此项为系统相应状态栏
 }

前后台通知

import {ipcMain,ipcRenderer} from 'electron'

在electron中有很多可用api,其中最重要的是:ipcMain和ipcRenderer,用于ui进程和系统进程的通信。 在vue内使用ipcRenderer.on('eventname') 接受系统发来的消息,用ipcRenderer.send('eventname') 发送通知给系统,同样ipcMain可以在主线程使用。

ipc通常结合自定义标题栏完成以下操作,或者其他需要操作窗口本身的事件

win.minimize() //最小化窗口
win.maximize() //最大化窗口
win.close() //关闭窗口
win.hide() //隐藏窗口

写在最后

其他方式就和常规的vue开发无异,关于系统和ui的交互需要多翻阅api文档 文档地址