Build and Optimize Hugo Binary
Let’s see how to optimize Hugo size binary as small as possible.
About Go Optimization
Optimizing the sizes of Hugo binary may useful for saving your storage, especially if you keep this on a remote server. There are several articles mentioned that go binary can be optimized as small as possible. According to the filippo.io, we can use the -s
and -w
linker flags to strip the debugging and save almost 28% of sizes. Petr Jahoda via itnext.io also mentioned that using UPX with --best --lzma
parameter will reduce about 21% of the original size.
Based on those articles, we can apply it to optimize Hugo binary and save more sizes. Take a look into my tweet below:
Install Required Packages
linux/amd64
environment- First of all, these are required packages to build Hugo binary:
Install required packages
a. Setup GoLang
1
wget https://go.dev/dl/go1.21.4.linux-amd64.tar.gz && sudo tar -C /usr/local -xzf go1.21.4.linux-amd64.tar.gz
b. Setup UPX
1
wget https://github.com/upx/upx/releases/download/v4.2.1/upx-4.2.1-amd64_linux.tar.xz && sudo tar -C /usr/local -xf upx-4.2.1-amd64_linux.tar.xz --transform 's/upx-4.2.1-amd64_linux/upx/'
Add all environment into
.profile
1 2 3
export PATH=$PATH:/usr/local/go/bin export PATH=$PATH:$HOME/go/bin export PATH=$PATH:/usr/local/upx
Build Hugo Binary
Download latest Hugo source
1
git clone https://github.com/gohugoio/hugo -b master && cd hugo
Export all required go environment
1
export CGO_ENABLED="1"
Build go binary with
-s
and-w
linker flags1
go install -ldflags="-s -w" --tags extended
Optimize Hugo binary with upx
1
upx --best --lzma "$HOME/go/bin/hugo"
Tips
If you want instant build, you can use my script below:
|
|
The output file will be in the bin/$(go env GOARCH)/hugo
.