从零开始创建Angular+Tauri项目

浏览:67次 评论:0次 日期:2025年11月14日 15:10:29 作者:管理员

1、创建Anguar

ng new MyNgxTauriProjectName --routing --skip-tests --style=scss --ssr=false --zoneless=true

2、安装Tauri

# 安装
npm install -D @tauri-apps/cli
# 初始化
npx tauri init
✔ What is your app name? · simple-aichat
✔ What should the window title be? · simple-aichat
? Where are your web assets (HTML/CSS/JS) located, relative to the "<current dir>/src-tauri/tauri.conf.json" file that w✔ Where are your web assets (HTML/CSS/JS) located, relative to the "<current dir>/src-tauri/tauri.conf.json" file that will be created? · ../dist/MyNgxTauriProjectName/browser 【PS:这里需要修改】
✔ What is the url of your dev server? · http://localhost:4200
✔ What is your frontend dev command? · npm run dev
✔ What is your frontend build command? · npm run build

3、安装核心依赖

npm i @tauri-apps/api @tauri-apps/plugin-opener
# 如果用不上可以不安装
## @tauri-apps/api 是 Tauri 的核心 JavaScript 库,是前端与后端通信的基础。
## @tauri-apps/plugin-opener 是一个 可选的插件,用于实现特定的功能,例如让系统默认浏览器打开链接。

4、修改package.json

{
    "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "watch": "ng build --watch --configuration development",
        "tauri": "tauri" <- 新的代码
    }
}

5、修改src-tauri/tauri.conf.json

{
    "identifier": "com.xxx.dev",                                 <- 这里需要修改,要不然打包失败
    "build": {
        "beforeDevCommand": "npm run start",                     <- 这里需要修改
        "devUrl": "http://localhost:4200",                       <- 这里需要修改
        "beforeBuildCommand": "npm run build",                   <- 这里需要修改
        "frontendDist": "../dist/MyNgxTauriProjectName/browser"  <- 这里需要修改
    }
}

6、启动

npm run tauri dev
# 这里会下载一些依赖,时间长很正常

7、打包

npm run tauri build

打包后的产物在【src-tauri\target\release】目录下

7、优化体积

# Cargo.toml 文件
[profile.release]
# 优先优化体积
opt-level = "s"
# 启用链接时优化
lto = true
# 牺牲编译速度,换取更小的体积
codegen-units = 1
# 遇到 Panic 时直接中止,而不是展开
panic = "abort"
# 剥离调试符号
strip = true

# tauri.conf.json 文件(建议不要使用这个,开启后差不多能节省350kb左右)
{
    "build": {
        "removeUnusedCommands": true   <- Tauri-CLI 会移除未在前端调用的 Rust 命令
    }
}

优化前后对比

优化前优化后
app.exe8387kb2777kb
msi2848kb1572kb
nsis1864kb1097kb

发表评论

Angular中文博客

分享让你更聪明