vue3前端开发系列 - electron开发桌面程序(2023-10月最新版)

1. 说明

本次安装使用的环境版本如下:

组件版本
nodejs18.16.1
npm9.5.1
electron26.3.0
electron-builder24.6.4

2. 创建项目

我是先用pnpm创建了一个vue3+vite+ts项目,然后后续安装的时候使用pnpm安装electron一直有问题。
后来改用npm安装electron才可以的。
还有nodejs的版本问题,这里安装的electron版本是26.3.0,推荐使用nodejs的版本为18.16.1。
否则,可能会出现各种奇奇怪怪的问题。

在安装electron electron-builder时,可能会出现网络连接问题,请配置阿里的源。

pnpm config set registry http://registry.npmmirror.com
npm config set registry http://registry.npmmirror.com
npm config set ELECTRON_MIRROR https://registry.npmmirror.com/-/binary/electron/

npm的config如下:
在这里插入图片描述

pnpm create vite
#输入项目名
Project name: electron-vue-vite
# 选择前端框架
Select a framework: Vue
# 选择语言
Select a variant: Typescript

# 使用npm安装包
npm install

# 安装样式
npm i sass -D

# 这里一定要大写D
npm i electron@v26.3.0 electron-builder -D

# 为了解决同时启动2个服务,以及白屏问题
npm i wait-on concurrently cross-env -D

3. 创建文件夹electron

在根目录创建文件夹electron

3.1 编写脚本electron.js

创建electron/electron.js

// electron/electron.js
const path = require('path');
const { app, BrowserWindow } = require('electron');

app.commandLine.appendSwitch('lang', 'zh-CN') 
const isDev = process.env.IS_DEV == "true" ? true : false;

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    },
  });

  // and load the index.html of the app.
  // win.loadFile("index.html");
  mainWindow.loadURL(
    isDev
      ? 'http://localhost:5173/'
      : `file://${path.join(__dirname, '../dist/index.html')}`
  );
  // Open the DevTools.
  if (isDev) {
    mainWindow.webContents.openDevTools();
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

3.2 编写脚本proload.js

创建electron/proload.js

// electron/preload.js

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})

4. 修改package.json

4.1 删除type

删除 “type”:“module” 这行,很重要,否则启动会报错。

4.2 修改scripts

直接用下面覆盖

  "scripts": {
    "dev": "vite --host",
    "build": "vite build",
    "serve": "vite preview",
    "electron": "wait-on tcp:5173 && cross-env IS_DEV=true electron .",
    "electron:dev": "concurrently -k \"cross-env BROWSER=none npm run dev\" \"npm run electron\"",
    "electron:build.win": "npm run build && electron-builder --win --dir",
    "electron:build.linux": "npm run build && electron-builder --linux appImage",
    "electron:build.test": "npm run build && electron-builder --dir",
    "electron:build.exe": "npm run build && electron-builder --win"
  },

注意点:wait-on后面监控的tcp端口要和启动的端口保持一致。

4.3 完整的配置如下

package.json

{
  "name": "electron-vue-vite",
  "author": "硅谷工具人",
  "private": true,
  "version": "0.0.0",
  "main": "electron/electron.js",
  "scripts": {
    "dev": "vite --host",
    "build": "vite build",
    "serve": "vite preview",
    "electron": "wait-on tcp:5173 && cross-env IS_DEV=true electron .",
    "electron:dev": "concurrently -k \"cross-env BROWSER=none npm run dev\" \"npm run electron\"",
    "electron:build.win": "npm run build && electron-builder --win --dir",
    "electron:build.linux": "npm run build && electron-builder --linux appImage",
    "electron:build.test": "npm run build && electron-builder --dir",
    "electron:build.exe": "npm run build && electron-builder --win"
  },
  "dependencies": {
    "vue": "^3.3.4"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.4.0",
    "concurrently": "^8.2.1",
    "cross-env": "^7.0.3",
    "electron": "^26.3.0",
    "electron-builder": "^24.6.4",
    "sass": "^1.69.2",
    "typescript": "^5.2.2",
    "vite": "^4.4.11",
    "vue-tsc": "^1.8.18",
    "wait-on": "^7.0.1"
  },
  "build": {
    "appId": "com.ggtool.knote",
    "productName": "KNote",
    "copyright": "Copyright © 2023 ${author}",
    "mac": {
      "category": "public.app-category.utilities"
    },
    "nsis": {
      "oneClick": false,
      "allowToChangeInstallationDirectory": true
    },
    "files": [
      "dist/**/*",
      "electron/**/*"
    ],
    "directories": {
      "buildResources": "assets",
      "output": "dist_electron"
    }
  }
}

5. 修改App.vue

这里指定容器的高度和宽带为800*600,和electron.js中createWindow设置保持相同。

<template>
  <HelloWorld class="container"/>
</template>

<script setup lang="ts">
import HelloWorld from "./components/HelloWorld.vue"
</script>
<style lang="scss" scoped>
.container{
  min-width:800px;
  min-height: 600px;
}
</style>

6. 修改vite.config.ts

在defineConfig中添加

base: process.env.ELECTRON=="true" ? './' : "./",

7. 启动

npm run electron:dev

在这里插入图片描述

8. 打包安装

打包win客户端,绿色包,直接拷贝使用的。

npm run electron:build.win

在这里插入图片描述

打包exe安装包,指定安装路径安装

npm run electron:build.exe

在这里插入图片描述

启动页面
在这里插入图片描述

9. 项目公开地址

项目已传gitee上,可以直接clone使用,欢迎点star。

https://gitee.com/ggtool/electron-vue-vite

10. 疑难问题

10.1 npm ERR! ELECTRON_MIRROR is not a valid npm option

执行命令npm config set ELECTRON_MIRROR https://registry.npmmirror.com/-/binary/electron/ 报错:
npm ERR! ELECTRON_MIRROR is not a valid npm option
使用npm config ls 找到.npmrc的位置:
在这里插入图片描述
打开后,加入下面一行:

ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

硅谷工具人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值