Trae怎么打包应用

Trae怎么打包应用

Python 后端 + React/Vue/Angular SPA 前端打包成单个 .exe。下面是几种主流方案的对比和推荐做法:

方案对比

方案 原理 优点 缺点
PyInstaller + 静态前端 PyInstaller 打包 Python 为 .exe,前端构建产物内嵌 成熟稳定,社区大 体积较大(50-200MB),启动稍慢
Nuitka + 静态前端 Nuitka 将 Python 编译为 C 再编译为二进制 性能更好,不易被反编译 编译慢,兼容性需测试
PyOxidizer + 静态前端 Rust 编写的打包器,嵌入 Python 解释器 体积小,启动快 配置较复杂,生态较小
cx_Freeze + 静态前端 类似 PyInstaller 的替代方案 可定制性强 社区较小

推荐方案:PyInstaller(最成熟)

整体思路

前端(React/Vue)→ npm run build → dist/ (静态文件)
                                            ↓
后端(Python)    → 用 Flask/FastAPI 托管 dist/
                                            ↓
PyInstaller      → 打包为单个 .exe

Step 1: 前端构建

cd frontend
npm run build
# 产出 dist/ 目录(html, js, css 等静态文件)

Step 2: 后端托管前端静态文件

以 FastAPI 为例:

# main.py
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import os

app = FastAPI()

# API 路由
@app.get("/api/hello")
def hello():
    return {"message": "Hello from backend"}

# 托管前端静态资源
# 将前端 build 产物复制到 backend/static/ 目录
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")

app.mount("/assets", StaticFiles(directory=os.path.join(STATIC_DIR, "assets")), name="assets")

@app.get("/{full_path:path}")
def serve_frontend(full_path: str):
    """SPA fallback:所有非 API 路由返回 index.html"""
    file_path = os.path.join(STATIC_DIR, full_path)
    if os.path.isfile(file_path):
        return FileResponse(file_path)
    return FileResponse(os.path.join(STATIC_DIR, "index.html"))

Step 3: 项目结构

my-project/
├── frontend/           # 前端源码
│   ├── src/
│   ├── package.json
│   └── vite.config.js
├── backend/
│   ├── main.py         # FastAPI 入口
│   ├── static/         # ← 前端 build 产物复制到这里
│   │   ├── index.html
│   │   └── assets/
│   ├── requirements.txt
│   └── ...
└── build.spec          # PyInstaller 配置(可选)

Step 4: 用 PyInstaller 打包

cd backend

# 安装 PyInstaller
pip install pyinstaller

# 方式 A:快速单文件打包
pyinstaller --onefile --name my-app main.py

# 方式 B:更精细的控制(推荐)
pyinstaller --onefile ^
  --name my-app ^
  --add-data "static;static" ^
  --hidden-import uvicorn.logging ^
  --hidden-import uvicorn.loops ^
  --hidden-import uvicorn.loops.auto ^
  --hidden-import multipart ^
  main.py

关键参数说明:

  • --onefile — 打包为单个 .exe
  • --add-data "static;static" — 将前端静态文件嵌入(注意 Windows 用 ; 分隔,Linux/Mac 用 :)
  • --hidden-import — 解决动态导入缺失的问题
  • --icon app.ico — 可选,设置 exe 图标

Step 5: 运行

打包完成后,产物在 dist/my-app.exe,双击即可运行。后端启动后会自动托管前端页面,浏览器访问 http://localhost:8000。

进阶优化

减小体积

# 使用虚拟环境,只安装必要的包
python -m venv venv
venv\Scripts\activate
pip install fastapi uvicorn pyinstaller
pyinstaller --onefile main.py

用 .spec 文件精细控制

# build.spec
a = Analysis(
    ['main.py'],
    datas=[('static', 'static')],
    hiddenimports=['uvicorn.logging', 'uvicorn.loops.auto', 'multipart'],
)
exe = EXE(
    a,
    name='my-app',
    console=False,        # 不显示命令行窗口
    icon='app.ico',
    onefile=True,
)

自动构建脚本(build.bat)

@echo off
echo === Building frontend ===
cd ..\frontend
call npm run build
xcopy /E /Y dist ..\backend\static\

echo === Building exe ===
cd ..\backend
call venv\Scripts\activate
pyinstaller build.spec --clean

echo === Done! ===
echo Output: backend\dist\my-app.exe

如果你想要更好的体验

如果你希望做成带窗口的桌面应用(而不是命令行程序 + 浏览器),可以考虑 Tauri(Rust 后端)或 Electron(Node.js 后端)。但这两个都需要重写后端逻辑,不如 PyInstaller 方案对现有 Python 代码友好。