我有一个打包好的前端项目,可以是 vue 也可以是 react ,现在需要变成一个桌面端 exe 应用,该如何做?
这里选用 pywebview + pyinstaller ,不使用 electron ,是因为 electron 相对麻烦一些,并且打出来的包要大很多;
安装
先要安装 python 环境,就可以使用 pip 了,然后安装以下两个包
pip install pywebview
pip install pyinstaller
两个目录
在项目根目录下准备两个目录
dist # 存放最终打包后得到的 exe
web_dist # 存放前端打包后的构建文件
两个文件
在项目根目录下准备两个文件
- main.py 将界面显示到 pywebview 中
# main.py
import webview
from webview import screens
window = None
class Api:
def __init__(self):
self.cancel_heavy_stuff_flag = False
# 可以加一些注入的逻辑接口
if __name__ == '__main__':
screen = screens[0]
width = screen.width
height = screen.height
api = Api()
webview.settings = {
'OPEN_DEVTOOLS_IN_DEBUG': True,
# 一些其他配置,查文档
}
# 打包配置
window = webview.create_window(
'我的客户端', './web_dist/index.html', fullscreen=True, width=int(width), height=int(height))
browser = webview.start(http_server=False, debug=True)
# 开发配置
# window = webview.create_window(
# '我的应用', 'http://localhost:5173/', width=int(width), height=int(height), js_api=api)
# browser = webview.start(debug=True)
- topackage.py 将 webview 界面打包成 exe ;
# topackage.py
import base64
import os
from PyInstaller.__main__ import run
def package():
basePath = os.path.abspath(__file__)
print(basePath)
basePath = basePath[:basePath.rfind("\")]
print(basePath)
opts = [
# 字符串前加“r”,防止字符转义
'--clean',
# -F, –onefile 打包一个单个文件
'-F',
# 要打包的Python文件
r'{}\main.py'.format(basePath),
# # -w 不使用窗口
'-w',
# --icon 指定exe文件的图标
r'--icon',r'{}\web_dist\favicon.ico'.format(basePath),
# --upx-dir 使用upx压缩
# r'--upx-dir', 'upx393w',
# --add-data 指定要包含的资源文件。
# “C:\Windows\System32\sciter.dll”为资源文件原本所在路径(source)。
# “.”为相对于exe文件的路径(destination),在这里“.”为同一目录的意思。
# source路径与destination路径以英文状态下分号“;”隔开。
# r'--add-data', 'C:\Windows\System32\sciter.dll;.',
# r'--add-binary', r'{}\templates;templates'.format(base),
r'--add-binary', r'{}\web_dist;web_dist'.format(basePath),
# r'--add-binary', r'{}\autoit;autoit'.format(base),
# r'--add-data', r'{}\templates;templates'.format(base),
r'--add-data', r'{}\web_dist;web_dist'.format(basePath),
# r'--add-data', r'{}\autoit;autoit'.format(base)
# 指定exe名称
r'--name', "我的应用app"
]
run(opts)
if __name__ == '__main__':
package()
构建
在项目根目录运行 cmd ,执行如下命令
python topackage.py
稍等片刻就可以看到 dist 目录下的 exe 文件了。