Contents

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

Info
I wrote this only for linux/amd64 environment
  1. First of all, these are required packages to build Hugo binary:
  1. 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/'
    
  2. 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

  1. Download latest Hugo source

    1
    
    git clone https://github.com/gohugoio/hugo -b master && cd hugo
    
  2. Export all required go environment

    1
    
    export CGO_ENABLED="1"
    
  3. Build go binary with -s and -w linker flags

    1
    
    go install -ldflags="-s -w" --tags extended
    
  4. 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:

1
wget https://raw.githubusercontent.com/khusika/khusika.github.io/master/build && ./build

The output file will be in the bin/$(go env GOARCH)/hugo.

Messages from UPX
False positive antivirus alerts of official UPX releases (Windows only). See #437