Go 實戰|使用 Wails 構建輕量級的桌面應用:仿微信登錄界面 Demo

概述

本文探討 Wails 框架的使用,從搭建環境到開發,再到最終的構建打包,本項目源碼 GitHub 地址:https://github.com/mazeyqian/go-run-wechat-demo

前言

Wails 是一個跨平臺桌面應用開發框架,他允許開發者利用 Go 的性能優勢,並結合任何前端技術棧,如 ReactVueSvelte,來創建桌面應用。

對於桌面應用,Electron 長久以來一直是主流選擇,他使用 Web 前端技術構建跨平臺的桌面應用。然而,Electron 有着較大的內存佔用和應用體積,這讓 Wails 成爲了輕量級的替代方案。

Wails 的顯著優勢:

  1. 更小的應用體積:Wails 編譯的應用程序通常比 Electron 更小,這意味着更快的下載速度和啓動時間,以及更低的運行時資源消耗。
  2. 原生性能:Go 提供了接近 C 語言的性能,這使得 Wails 應用能夠更高效地運行,尤其是在處理併發任務和系統級操作時。
  3. 簡化的構建過程:Wails 簡化了構建過程,只需一條命令就可以將應用打包爲可執行文件,無需額外的配置或依賴。
  4. 優秀的開發體驗:和開發 Web 前端應用一樣的實時改動反饋,並且可以在瀏覽器中開發桌面應用。
  5. 原生用戶界面元素:Wails 支持使用系統原生的用戶界面元素,提供一致的用戶體驗。
  6. 靈活的前端選擇:可以選擇開發者熟悉的任何前端框架來開發桌面應用。

Components of a Wails App

創建一個 Wails 項目

在開始創建 Wails 項目之前,需要確保系統中已經安裝了 Go 和 Node.js,因爲 Wails 依賴這兩者來構建桌面應用。以下是安裝 Wails 框架和創建新項目的步驟。

安裝 Wails

go install github.com/wailsapp/wails/v2/cmd/wails@latest

驗證安裝結果:

wails version

也可以通過 wails doctor 來檢查是否所有必要的依賴都已正確安裝。

# Wails
# ...
# System
# ...
# Dependencies
# ...
# Diagnosis
# ...
SUCCESS  Your system is ready for Wails development!

我的本地開發版本:

# Version
Wails v2.6.0
Go v1.19.1
Node.js v16.19.0
npm v8.19.3

創建新項目

使用 Wails CLI 創建一個名爲 go-run-wechat-demo 的新項目:

wails init -n go-run-wechat-demo -t react-ts

項目結構

項目結構

  • main.goapp.go:Go 應用程序,處理業務邏輯、數據管理和與前端的通信。
  • frontend:包含前端的所有代碼,使用 React、Vue 或你選擇的任何其他框架,負責用戶界面和與用戶的交互。
  • go.modgo.sum:Go 的模塊依賴文件。
  • wails.json:Wails 項目的配置文件,定義瞭如何構建和打包應用。
  • build:用於存放構建後的應用程序和相關資源。

項目開發:仿微信登錄界面

進入開發模式

進入項目根目錄,輸入並執行 wails dev 命令,首次執行會安裝前後端依賴,執行成功後可以看到默認應用頁面。

默認應用頁面

並且可以在瀏覽器調試頁面:

To develop in the browser and call your bound Go methods from Javascript, navigate to: http://localhost:34115

任何代碼修改也都能夠熱更新:

1:42:21 PM [vite] hmr update /src/App.tsx

修改代碼

窗口樣式和佈局

爲了模仿微信登錄界面,在 main.go 文件中,通過 Wails 框架的配置選項修改了應用程序窗口的尺寸 Width&Height、背景色 BackgroundColour 和標題 Title

main.go

func main() {
	// Create an instance of the app structure
	app := NewApp()

	// Create application with options
	err := wails.Run(&options.App{
		Title:  "WeChat",
		Width:  280,
		Height: 400,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 1},
		OnStartup:        app.startup,
		Bind: []interface{}{
			app,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}

後端實現

本次 Demo 主要實現兩個功能,登錄和切換賬號;這兩個方法可以通過前端 JavaScript 調用。返回的字符串可以用於在 UI 中顯示相應的狀態消息給用戶。在文件 app.go 中添加這兩個方法。

// Log In Success
func (a *App) LogInSuccess(name string) string {
	return fmt.Sprintf("Welcome %s, You are logged in!", name)
}

// Switch Account Success
func (a *App) SwitchAccountSuccess() string {
	return "You have switched accounts!"
}

在 Wails 開發模式下,會自動將 Go 結構體轉換爲 TypeScript 模塊。

// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT

export function LogInSuccess(arg1:string):Promise<string>;

export function SwitchAccountSuccess():Promise<string>;

前端實現

修改 frontend/src/App.tsx 文件,添加相關邏輯:

import {useState} from "react";
import logo from "./assets/images/logo-universal-w256.jpg";
import "./App.css";
import {LogInSuccess, SwitchAccountSuccess} from "../wailsjs/go/main/App";

function App() {
    const [resultText, setResultText] = useState("");
    const name = "除";
    const updateResultText = (result: string) => setResultText(result);

    function logIn() {
        LogInSuccess(name).then(updateResultText);
    }

    function switchAccount() {
        SwitchAccountSuccess().then(updateResultText);
    }

    return (
        <div id="App">
            <img src={logo} id="logo" alt="logo"/>
            <div id="result" className="result name">{resultText || name}</div>
            <button className="btn log-in" onClick={logIn}>Log In</button>
            <button className="btn switch-account" onClick={switchAccount}>Switch Account</button>
        </div>
    )
}

export default App

並且修改了 CSS 樣式文件 frontend/src/App.css 來適配界面:

.btn {
    display: block;
    margin: 0 auto;
    padding: 0;
    text-align: center;
    border: none;
    font-size: 14px;
}

.log-in {
    width: 200px;
    height: 36px;
    line-height: 36px;
    color: #ffffff;
    background-color: hsla(148, 61%, 46%, 1);
    border-radius: 4px;
    margin-top: 70px;
}

.switch-account {
    background-color: #ffffff;
    color: rgb(89, 107, 144);
    margin-top: 22px;
}

此時界面如圖:

界面

嘗試操作 Log In:

Log In

嘗試操作 Switch Account:

Switch Account

底部圖標:

底部圖標

打包應用

在項目根目錄,運行 wails build 即可打包當前環境下的應用程序。但是在開發模式下,已經有了一些緩存文件,可以配合 -clean 來清理 build/bin 目錄:

wails build -clean

打包 macOS App:

wails build -platform=darwin/amd64

打包 Windows 程序:

wails build -platform=windows/amd64

打包

使用 create-dmg 爲 macOS 創建 .dmg 文件:

create-dmg WeChat.dmg WeChat.app

macOS

以上文件可以進入 Releases 頁面查看:

https://github.com/mazeyqian/go-run-wechat-demo/releases/tag/v1.0.0

Releases

總結

Wails 框架提供了一種簡潔而強大的方式,讓開發者能夠利用 Go 的性能優勢和 Web 前端的靈活性,從而能夠使用更高效、更輕量級的方法來構建跨平臺的桌面應用。

版權聲明

本博客所有的原創文章,作者皆保留版權。轉載必須包含本聲明,保持本文完整,並以超鏈接形式註明作者後除和本文原始地址:https://blog.mazey.net/4499.html

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章