optimizing-tauri-binary-size

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tauri Binary Size Optimization

Tauri二进制文件大小优化

This skill provides guidance on optimizing Tauri application binary sizes for production releases.
本技能为生产环境发布的Tauri应用提供二进制文件大小优化指导。

Why Tauri Produces Small Binaries

为什么Tauri能生成体积小巧的二进制文件

Tauri is designed from the ground up to produce minimal binaries:
  1. Native Webview: Uses the operating system's native webview instead of bundling Chromium (unlike Electron)
  2. Rust Backend: Compiles to efficient native code with no runtime overhead
  3. Tree Shaking: Only includes code that is actually used
  4. No V8 Engine: Leverages existing system components rather than bundling a JavaScript engine
Tauri从设计之初就致力于生成最小化的二进制文件:
  1. 原生Webview:使用操作系统自带的原生webview,而非像Electron那样打包Chromium
  2. Rust后端:编译为高效的原生代码,无运行时开销
  3. 摇树优化:仅包含实际用到的代码
  4. 无V8引擎:利用现有系统组件,而非打包JavaScript引擎

Size Comparison

大小对比

FrameworkMinimum Binary Size
Tauri~3-6 MB
Electron~120-180 MB
NW.js~80-100 MB
The dramatic size difference comes from Tauri's architectural decision to use native system webviews rather than bundling a full browser engine.
框架最小二进制文件大小
Tauri~3-6 MB
Electron~120-180 MB
NW.js~80-100 MB
这种巨大的大小差异源于Tauri选择使用原生系统webview而非打包完整浏览器引擎的架构决策。

Cargo.toml Optimization Settings

Cargo.toml优化设置

Configure release profile settings in
src-tauri/Cargo.toml
to minimize binary size.
src-tauri/Cargo.toml
中配置release模式的配置项,以最小化二进制文件大小。

Recommended Stable Toolchain Configuration

推荐的稳定版工具链配置

toml
[profile.release]
codegen-units = 1    # Compile crates one at a time for better LLVM optimization
lto = true           # Enable link-time optimization across all crates
opt-level = "s"      # Optimize for binary size (alternative: "z" for even smaller)
panic = "abort"      # Remove panic unwinding code
strip = true         # Strip debug symbols from final binary
toml
[profile.release]
codegen-units = 1    # 逐个编译 crate,以获得更好的LLVM优化效果
lto = true           # 启用跨所有crate的链接时优化
opt-level = "s"      # 针对二进制文件大小进行优化(备选:"z"可获得更小体积)
panic = "abort"      # 移除panic展开代码
strip = true         # 从最终二进制文件中剥离调试符号

Configuration Options Explained

配置项说明

OptionValuesDescription
codegen-units
1
Reduces parallelism but allows LLVM to perform better whole-program optimization
lto
true
,
"thin"
,
"fat"
Link-time optimization;
true
or
"fat"
produces smallest binaries
opt-level
"s"
,
"z"
,
"3"
"s"
balances size/speed,
"z"
prioritizes size,
"3"
prioritizes speed
panic
"abort"
Removes panic handler code, reducing binary size
strip
true
,
"symbols"
,
"debuginfo"
Removes symbols and debug information from binary
选项可选值描述
codegen-units
1
降低并行编译度,但允许LLVM执行更优的全程序优化
lto
true
,
"thin"
,
"fat"
链接时优化;
true
"fat"
可生成最小体积的二进制文件
opt-level
"s"
,
"z"
,
"3"
"s"
平衡大小与速度,
"z"
优先考虑体积,
"3"
优先考虑速度
panic
"abort"
移除panic处理代码,减小二进制文件大小
strip
true
,
"symbols"
,
"debuginfo"
从二进制文件中移除符号和调试信息

Nightly Toolchain Options

夜间版工具链选项

For projects using the nightly Rust toolchain, additional optimizations are available:
toml
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true
trim-paths = "all"    # Remove file path information from binary

[profile.release.build-override]
opt-level = "s"       # Also optimize build scripts
You can also set rustflags for additional control:
toml
[profile.release]
rustflags = ["-Cdebuginfo=0", "-Zthreads=8"]
对于使用Rust夜间版工具链的项目,可使用额外的优化选项:
toml
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true
trim-paths = "all"    # 从二进制文件中移除文件路径信息

[profile.release.build-override]
opt-level = "s"       # 同时优化构建脚本
你也可以设置rustflags以获得更多控制:
toml
[profile.release]
rustflags = ["-Cdebuginfo=0", "-Zthreads=8"]

Tauri Build Configuration

Tauri构建配置

Remove Unused Commands (Tauri 2.4+)

移除未使用的命令(Tauri 2.4+)

Tauri 2.4 introduced the ability to automatically remove code for commands not permitted in your Access Control List (ACL). Add this to
tauri.conf.json
:
json
{
  "build": {
    "removeUnusedCommands": true
  }
}
This feature:
  • Analyzes your ACL configuration
  • Removes Tauri command handlers that are not allowed
  • Reduces binary size without changing functionality
  • Works automatically during release builds
Tauri 2.4引入了自动移除访问控制列表(ACL)中未允许的命令代码的功能。在
tauri.conf.json
中添加以下配置:
json
{
  "build": {
    "removeUnusedCommands": true
  }
}
该特性:
  • 分析你的ACL配置
  • 移除未被允许的Tauri命令处理器
  • 在不改变功能的前提下减小二进制文件大小
  • 在发布构建时自动生效

Minimal Feature Set

最小化功能集

Only enable Tauri features you actually need in
src-tauri/Cargo.toml
:
toml
[dependencies]
tauri = { version = "2", features = ["macos-private-api"] }
仅在
src-tauri/Cargo.toml
中启用你实际需要的Tauri功能:
toml
[dependencies]
tauri = { version = "2", features = ["macos-private-api"] }

Avoid enabling unnecessary features like:

避免启用不必要的功能,例如:

- "devtools" in production

- 生产环境中的"devtools"

- "protocol-asset" if not serving local assets

- 若不加载本地资源则不启用"protocol-asset"

- "tray-icon" if not using system tray

- 若不使用系统托盘则不启用"tray-icon"

undefined
undefined

Frontend Optimization

前端优化

While this skill focuses on Rust/Tauri optimization, frontend bundle size also affects the final application:
  1. Use a bundler: Vite, webpack, or similar with tree shaking
  2. Code splitting: Load features on demand
  3. Minimize dependencies: Audit and remove unused npm packages
  4. Compress assets: Optimize images and other static assets
虽然本技能主要聚焦于Rust/Tauri优化,但前端打包体积也会影响最终应用大小:
  1. 使用打包工具:Vite、webpack等支持摇树优化的工具
  2. 代码分割:按需加载功能模块
  3. 最小化依赖:审计并移除未使用的npm包
  4. 压缩资源:优化图片及其他静态资源

Build Commands

构建命令

Standard Release Build

标准发布构建

bash
cd src-tauri
cargo tauri build --release
bash
cd src-tauri
cargo tauri build --release

Using Nightly Toolchain

使用夜间版工具链

bash
cd src-tauri
cargo +nightly tauri build --release
bash
cd src-tauri
cargo +nightly tauri build --release

Check Binary Size

检查二进制文件大小

After building, check your binary size:
bash
undefined
构建完成后,检查你的二进制文件大小:
bash
undefined

macOS

macOS

ls -lh src-tauri/target/release/bundle/macos/.app/Contents/MacOS/
ls -lh src-tauri/target/release/bundle/macos/.app/Contents/MacOS/

Linux

Linux

ls -lh src-tauri/target/release/bundle/appimage/*.AppImage
ls -lh src-tauri/target/release/bundle/appimage/*.AppImage

Windows

Windows

dir src-tauri\target\release\bundle\msi*.msi
undefined
dir src-tauri\target\release\bundle\msi*.msi
undefined

Complete Example Configuration

完整示例配置

Here is a complete
src-tauri/Cargo.toml
optimized for minimal binary size:
toml
[package]
name = "my-tauri-app"
version = "0.1.0"
edition = "2021"

[dependencies]
tauri = { version = "2", features = [] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[build-dependencies]
tauri-build = { version = "2", features = [] }

[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true

[profile.release.package."*"]
opt-level = "s"
And corresponding
tauri.conf.json
:
json
{
  "productName": "my-tauri-app",
  "version": "0.1.0",
  "identifier": "com.example.my-tauri-app",
  "build": {
    "removeUnusedCommands": true,
    "beforeBuildCommand": "npm run build",
    "frontendDist": "../dist"
  },
  "bundle": {
    "active": true,
    "targets": "all",
    "icon": ["icons/icon.png"]
  }
}
以下是针对最小二进制文件大小优化的完整
src-tauri/Cargo.toml
配置:
toml
[package]
name = "my-tauri-app"
version = "0.1.0"
edition = "2021"

[dependencies]
tauri = { version = "2", features = [] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[build-dependencies]
tauri-build = { version = "2", features = [] }

[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true

[profile.release.package."*"]
opt-level = "s"
以及对应的
tauri.conf.json
json
{
  "productName": "my-tauri-app",
  "version": "0.1.0",
  "identifier": "com.example.my-tauri-app",
  "build": {
    "removeUnusedCommands": true,
    "beforeBuildCommand": "npm run build",
    "frontendDist": "../dist"
  },
  "bundle": {
    "active": true,
    "targets": "all",
    "icon": ["icons/icon.png"]
  }
}

Optimization Trade-offs

优化的权衡

SettingSize ImpactBuild TimeRuntime Performance
codegen-units = 1
SmallerSlowerBetter
lto = true
SmallerMuch slowerBetter
opt-level = "s"
SmallerSimilarSlightly slower
opt-level = "z"
SmallestSimilarSlower
panic = "abort"
SmallerFasterNo unwinding
strip = true
SmallerSimilarNo impact
设置对体积的影响构建时间运行时性能
codegen-units = 1
更小更慢更好
lto = true
更小慢很多更好
opt-level = "s"
更小相近略慢
opt-level = "z"
最小相近更慢
panic = "abort"
更小更快无展开功能
strip = true
更小相近无影响

Troubleshooting

故障排查

Binary Still Large

二进制文件仍然过大

  1. Check for debug builds: Ensure you are using
    --release
    flag
  2. Audit dependencies: Run
    cargo tree
    to see dependency graph
  3. Check for duplicate dependencies: Different versions of same crate
  4. Verify strip is working: Use
    file
    command to check for debug symbols
  1. 检查是否为调试构建:确保使用了
    --release
    参数
  2. 审计依赖:运行
    cargo tree
    查看依赖图谱
  3. 检查重复依赖:同一 crate 的不同版本
  4. 验证strip是否生效:使用
    file
    命令检查是否存在调试符号

Build Failures with LTO

启用LTO后构建失败

If
lto = true
causes build failures:
  • Try
    lto = "thin"
    as a fallback
  • Ensure sufficient memory (LTO is memory-intensive)
  • Update Rust toolchain to latest version
如果
lto = true
导致构建失败:
  • 尝试使用
    lto = "thin"
    作为备选方案
  • 确保有足够的内存(LTO非常消耗内存)
  • 将Rust工具链更新至最新版本

Nightly Features Not Working

夜间版功能无法工作

Ensure nightly is installed and active:
bash
rustup install nightly
rustup default nightly
确保夜间版已安装并激活:
bash
rustup install nightly
rustup default nightly

Or use +nightly flag with cargo commands

或者在cargo命令后添加+nightly参数

undefined
undefined

References

参考资料