Skip to content

Commit 4938262

Browse files
committed
chore: (WIP) Optimize WASM builds
1 parent ba40790 commit 4938262

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

cmd/rfw/build/build.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
_ "github.com/rfwlab/rfw/cmd/rfw/plugins/seo"
2121
_ "github.com/rfwlab/rfw/cmd/rfw/plugins/tailwind"
2222
_ "github.com/rfwlab/rfw/cmd/rfw/plugins/test"
23+
"github.com/rfwlab/rfw/cmd/rfw/utils"
2324
)
2425

2526
func Build() error {
@@ -68,13 +69,31 @@ func Build() error {
6869
if os.Getenv("RFW_DEVTOOLS") == "1" {
6970
args = append(args, "-tags=devtools")
7071
}
71-
args = append(args, "-o", filepath.Join(clientDir, "app.wasm"), ".")
72+
if !utils.IsDebug() {
73+
args = append(args, "-trimpath", "-ldflags=-s -w")
74+
}
75+
wasmPath := filepath.Join(clientDir, "app.wasm")
76+
args = append(args, "-o", wasmPath, ".")
7277
cmd := exec.Command("go", args...)
7378
cmd.Env = append(os.Environ(), "GOARCH=wasm", "GOOS=js")
7479
output, err := cmd.CombinedOutput()
7580
if err != nil {
7681
return fmt.Errorf("failed to build project: %s: %w", output, err)
7782
}
83+
if os.Getenv("RFW_SKIP_WASM_OPT") != "1" {
84+
if _, err := exec.LookPath("wasm-opt"); err == nil {
85+
tmpPath := filepath.Join(clientDir, "app.tmp.wasm")
86+
optCmd := exec.Command("wasm-opt", "-Oz", "--strip-debug", "-o", tmpPath, wasmPath)
87+
if optOutput, err := optCmd.CombinedOutput(); err != nil {
88+
return fmt.Errorf("failed to optimize wasm: %s: %w", optOutput, err)
89+
}
90+
if err := os.Rename(tmpPath, wasmPath); err != nil {
91+
return fmt.Errorf("failed to finalize optimized wasm: %w", err)
92+
}
93+
} else {
94+
utils.Info("warning: wasm-opt not found; skipping Wasm optimization")
95+
}
96+
}
7897

7998
if err := os.MkdirAll(hostDir, 0o755); err != nil {
8099
return fmt.Errorf("failed to create host build directory: %w", err)

docs/articles/getting-started/quick-start.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ The build command outputs:
120120
* `build/static/` – copied static files
121121
* `build/host/` – companion host binary
122122

123+
Outside of debug mode the build uses Go's `-trimpath` and `-ldflags="-s -w"` flags to strip debug information from the generated WebAssembly module. When [`wasm-opt`](https://github.com/WebAssembly/binaryen) is on your `PATH`, the CLI also runs `wasm-opt -Oz --strip-debug` to further shrink `app.wasm`. Set `RFW_SKIP_WASM_OPT=1` in the environment before invoking `rfw build` to skip the optimization step when troubleshooting or comparing unoptimized binaries.
124+
123125
## What You Learned
124126

125127
* Installing the CLI

0 commit comments

Comments
 (0)