1. 程式人生 > 其它 >Electron + Vue3 +Ant Design Vue 桌面應用從專案搭建到打包釋出

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

專案環境

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系統下進行打包