Electron + Vue3 +Ant Design Vue 桌面應用從項目搭建到打包發布


1.技術棧介紹

electron

electron使用 JavaScript,HTML 和 CSS 構建跨平台的桌面應用程序

官網: https://www.electronjs.org/

vue3

Vue (讀音 /vjuː/,類似於 view) 是一套用於構建用戶界面的漸進式框架

官網: https://v3.cn.vuejs.org/guide/introduction.html

Ant Design of Vue

是 Ant Design 的 Vue 實現,開發和服務於企業級后台產品。

官網: https://www.antdv.com/docs/vue/introduce

項目環境

image-20220416170354231

2. 項目搭建

命令窗口程序為: cmder 可以使用系統自帶powershell

yarn 設置淘寶源

yarn config set registry https://registry.npm.taobao.org -g 
yarn config set disturl https://npm.taobao.org/dist -g 
yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/ -g 

2.1 創建項目

yarn create vite
.....配置項目名稱和vue-ts風格
√ Project name: ... ov-client
√ Select a framework: » vue
√ Select a variant: » vue-ts

切換項目目錄, 運行項目

cd ov-client
yarn
yarn dev

2.2 安裝ant design vue

vscode打開項目, 打開終端端口(頂部菜單欄 Terminal-> New Terminal )

yarn add ant-design-vue

配置antd按需加載

yarn add unplugin-vue-components --dev

修改vite.config.ts 配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
//++
import ViteComponents from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    //++
    ViteComponents({
      resolvers: [
        AntDesignVueResolver(),
      ],
    }),
  ]
})

注意: 你可以使用 [unplugin-vue-components] 來進行按需加載。但是此插件無法處理非組件模塊,如 message,這種組件需要手動加載:

import { message } from 'ant-design-vue';
import 'ant-design-vue/es/message/style/css'; //vite只能用 ant-design-vue/es 而非 ant-design-vue/lib

測試ant-design-vue 是否正常

修改在項目src/App.vue

<script setup lang="ts">
</script>

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <p>Vue3 + Ant Design Vue3 演示項目</p>
  <a-button  type="primary">測試ant-design-vue 按鈕</a-button>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

2.3 安裝electron及工具包

yarn add electron --dev
yarn add wait-on  --dev //監控端口
yarn add cross-env --dev //

安裝成功package.json 如下

{
  "name": "ov-client",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "ant-design-vue": "^3.1.1",
    "vue": "^3.2.25"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.3.1",
    "cross-env": "^7.0.3",
    "electron": "^18.0.4",
    "typescript": "^4.5.4",
    "unplugin-vue-components": "^0.19.3",
    "vite": "^2.9.2",
    "vue-tsc": "^0.29.8",
    "wait-on": "^6.0.1"
  }
}

2.3.1 配置package

添加electron啟動命令和入口文件

  ...
  "main": "electron/main.js",
  "scripts": {
   ...
    "electron:dev": "wait-on tcp:3000 && cross-env NODE_ENV=development  electron ./",
  },

2.3.2 項目根創建 electron目錄, 新建main.js 和 preload.js

main.js

const { app, BrowserWindow, Menu, MenuItem } = require("electron");
const path = require("path");
const NODE_ENV = process.env.NODE_ENV;

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 980,
    height: 680,
    // transparent: true,
    // fullscreen: true,
    // frame: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });


  if (NODE_ENV === "development") {
    mainWindow.loadURL("http://localhost:8080/");
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadURL(`file://${path.join(__dirname, "../dist/index.html")}`);
  }
}

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

// 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", function () {
  if (process.platform !== "darwin") app.quit();
});

proload.js

//允許vue項目使用 ipcRenderer 接口, 演示項目中沒有使用此功能
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("ipcRender", ipcRenderer);

2.3.3 測試electron

yarn electron:dev

3.項目打包

安裝打包工具 electron-builder

yarn add electron-builder --dev

package.js 配置打包命令, 先打包vue項目再用electron-builder打包dist目錄

  "scripts": {
    ...
    "electron:build": "vue-tsc --noEmit && vite build && electron-builder",
  },
  "build": {
    "productName": "ovClient",
    "appId": "com.lvais",
    "copyright": "2022@sentangle",
    "directories": {
      "output": "output"
    },
    "files": [
      "dist/**/*",
      "electron/**/*"
    ],
    "nsis": {
      "oneClick": false,
      "allowElevation": true,
      "allowToChangeInstallationDirectory": true,
      "createDesktopShortcut": true
    },
    "linux": {}
  },

3.1 先打包vue3項目

yarn build
# 如果提示錯誤, 請設置tsconfig.json中 compilerOptions.isolatedModules= false
node_modules/@vue/reactivity/dist/reactivity.d.ts:26:15 - error TS2748: Cannot access ambient const enums when the '--isolatedModules' flag is provided.

3.2 electron-builder打包

yarn electron:build

打包成功了, output 生產文件

點擊win-unpacked/vmClient.exe 顯示以下窗口說明成功了

4 常見問題

4.1 electron-builder打包后頁面空白?

頁面中js等資源路徑不正確, 請配置 vite.config.ts 中base

export default defineConfig({
  base:"./",
})

4.2 打包過慢, 請配置yarn的淘寶源

yarn

yarn config set registry https://registry.npm.taobao.org -g 
yarn config set disturl https://npm.taobao.org/dist -g 
yarn config set electron_mirror https://npm.taobao.org/mirrors/electron/ -g 

4.3 window 無法打包linux安裝包

請將項目移植到linux系統下進行打包


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM