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

文章目录

  • [1. 说明](#1. 说明)
  • [2. 创建项目](#2. 创建项目)
  • [3. 创建文件夹electron](#3. 创建文件夹electron)
    • [3.1 编写脚本electron.js](#3.1 编写脚本electron.js)
    • [3.2 编写脚本proload.js](#3.2 编写脚本proload.js)
  • [4. 修改package.json](#4. 修改package.json)
    • [4.1 删除type](#4.1 删除type)
    • [4.2 修改scripts](#4.2 修改scripts)
    • [4.3 完整的配置如下](#4.3 完整的配置如下)
  • [5. 修改App.vue](#5. 修改App.vue)
  • [6. 修改vite.config.ts](#6. 修改vite.config.ts)
  • [7. 启动](#7. 启动)
  • [8. 打包安装](#8. 打包安装)
  • [9. 项目公开地址](#9. 项目公开地址)

1. 说明

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

组件 版本
nodejs 18.16.1
npm 9.5.1
electron 26.3.0
electron-builder 24.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
相关推荐
weixin_3823952335 分钟前
为小工厂量身打造:本地部署的物料管理系统带缺料计算
前端·制造
__zRainy__41 分钟前
解决pnpm v10+不自动构建
前端·pnpm·工程化
猫猫不是喵喵.1 小时前
Vue3 Props 属性
前端·javascript·vue.js
醉城夜风~2 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华3 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子5 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅5 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni6 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学7 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端