likes
comments
collection
share

Electron+vue3+vite+TS的结合使用记录

作者站长头像
站长
· 阅读数 19

Electron是一个桌面应用框架,使用js+css+html即可开发,并且可以打包出Mac,window,linux多个平台的应用,类似uniapp,一套代码多端覆盖

electron分为 主进程,渲染进程(web页面),我们可以通过IPC来通讯,其中开启渲染进程使用node后,也可以在渲染进程使用node方法

说明

想要让vue和electron结合使用,我在网上找了许多案例,其中有vue-elecron,还有一些等,但是这些都是使用webpack的而且很久很久几年没更新了

Electron+vue3+vite+TS的结合使用记录

最后找到了一个在更新的,并且star还比较多。electron + vue + vite + ts的模板github

使用

创建项目

npm create electron-vite

进入项目文件夹

cd electron-vite

安包

npm install  
# 这么操作的话,安包会很慢,虽然你设置了国内镜像,但是electron一些依赖还是会从npm官方进行下载,所以慢

安包慢可以先设置环境变量,我这里用的是yarn

Electron+vue3+vite+TS的结合使用记录

  1. 项目根目录下新建文件 .yarnrc
  2. 然后再文件里面写上以下代码
registry "https://registry.npm.taobao.org/"

electron_mirror "https://npm.taobao.org/mirrors/electron/"
electron_builder_binaries_mirror "http://npm.taobao.org/mirrors/electron-builder-binaries/"

然后可以安包了

yarn install  

这样就完成了项目初始化

yarn run dev   # 启动项目

目录结构

electron-vue
   src    为vue项目文件,渲染进程
   electron     为electron的主入口,主进程文件

原理

大家都知道vite的模式就是使用各种插件,那么这里也就是使用了一位大佬开发的vite插件叫 vite-plugin-electron进行了处理

// vite.config.ts
import { rmSync } from 'node:fs'
import vue from '@vitejs/plugin-vue'
import electron from 'vite-plugin-electron'
import renderer from 'vite-plugin-electron-renderer'
export default defineConfig(({ command }) => {
  rmSync('dist-electron', { recursive: true, force: true })

  const isServe = command === 'serve'
  const isBuild = command === 'build'
  const sourcemap = isServe || !!process.env.VSCODE_DEBUG
  return {
    plugins: [
      vue(),
      electron([
        {
          // Electron入口文件
          entry: 'electron/main/index.ts',
          onstart(options) {
            if (process.env.VSCODE_DEBUG) {
              console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')
            } else {
              options.startup()
            }
          },
          vite: {
            build: {
              sourcemap,
              minify: isBuild,
              outDir: 'dist-electron/main',
              rollupOptions: {
                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
              },
            },
          },
        },
        {
          entry: 'electron/preload/index.ts',
          onstart(options) {
            // 当Preload-Scripts构建完成时,通知Renderer-Process重新加载页面
            // 而不是重新启动整个应用程序。
            options.reload()
          },
          vite: {
            build: {
              sourcemap: sourcemap ? 'inline' : undefined, // #332
              minify: isBuild,
              outDir: 'dist-electron/preload',
              rollupOptions: {
                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
              },
            },
          },
        }
      ]),
      // 在渲染进程中使用Node.js API
      renderer(),
      ]
    }})

大概就是这些配置项了,在模板中这些都已经写好了

在渲染进程中开启node

配置nodeIntegration: true, contextIsolation: false 这两项即可

const electron = require("electron");
const win = new electron.BrowserWindow({
    title: "Main window",
    icon: "favicon.ico",
    webPreferences: {
      // 警告:在生产环境中启用nodeIntegration并禁用contextIsolation是不安全的
      // 考虑使用contextBridge.exposeInMainWorld
      // 阅读更多 https://www.electronjs.org/docs/latest/tutorial/context-isolation
      nodeIntegration: true,  // 设置true
      contextIsolation: false  // 设置false  
      // webSecurity: false, // 允许跨域
    }
  });

问题记录

最后更新时间 2023-4-11

安装electron慢

在前面使用步骤中 已经有记录解决方法

node模块报错

有一些node模块在vue页面中使用会报错找不到,其实开启渲染进程node后,是可以使用的,只不过vite打包时候当普通模块打包处理了,所以需要配置为外部引用

例如ws模块 就会出问题提示不能在浏览器运行

用到插件vite-plugin-externals

yarn add vite-plugin-externals

配置vite.config.ts

import { viteExternalsPlugin } from 'vite-plugin-externals'
export default defineConfig(({ command }) => {
    //....此处省略其它代码
    return {
    plugins: [
    vue(),
    // 配置外部引入模块,这样打包的时候就不会被打包
    viteExternalsPlugin({
        ws: 'ws', // 例如puppeteer-core依赖node的ws模块
      })
    ],
})

然后在index.html文件中 引入ws模块就行啦

<script>
    // 一些nodejs模块需要在这里引入,并在vite.config.js中配置externals,也就是cdn引入
    var ws = require('ws')  // 利用var挂到全局去
  </script>
  <script type="module" src="/src/main.ts"></script> <!-- 写在这前面 -->

Mac下复制粘贴快捷键失效

在mac环境中,electron窗口中,如果替换了默认的菜单,那么复制粘贴的快捷键会失效,解决方法是添加菜单,并给菜单添加快捷键,代码如下

// electron/main/index.ts
import { Menu, MenuItem } from 'electron'
const menu = new Menu()  // 创建菜单
// 判断当前为mac系统则添加以下菜单
if (process.platform === "darwin") {
  menu.append(new electron.MenuItem({
    label: "编辑",
    submenu: [
      { role: "undo", label: "撤销" },
      { role: "redo", label: "重做" },
      { type: "separator", label: "分割线" },
      { role: "cut", label: "剪切" },
      { role: "copy", label: "复制" },
      { role: "paste", label: "粘贴" },
      { role: "delete", label: "删除" }
    ]
  }));
}
 Menu.setApplicationMenu(menu)

最后

大家有什么electron的问题欢迎一起讨论


目前使用electron+puppeteer开发的一款应用

Electron+vue3+vite+TS的结合使用记录