點燈坊

失くすものさえない今が強くなるチャンスよ

Minimizing HTML under Production

Sam Xiao's Avatar 2022-02-10

Minimizing HTML is provided by Hugo. We can minimize HTML under production.

Version

Hugo 0.92

Create New Site

$ hugo new site hugo-minimize --format json
  • hugo new site : create a new site with default skeloton
  • --format json : use JSON as Hugo config format

minify000

Add Packages

$ npm install -D prettier
  • prettier : code formatter for HTML/CSS/JavaScript

minify001

Prettier

minimize011

WebStorm -> Preferences -> Language & Frameworks -> Prettier

  • Prettier package : WebStorm will get a path automatically after installing Prettier
  • Rule for files : add html for Prettier to work with TailwindCSS
  • On Reformat Code action : run Prettier with the default Reformat code action
  • On save : run Prettier on save

After checking On Reformat Code action and On save, Prettier works as the default code formatter instead of WebStorm internal formatter

Hugo Config

config.json

{
  "baseURL": "http://example.org/",
  "languageCode": "en-us",
  "title": "My New Hugo Site",
  "minify": {
    "tdewolff": {
      "html": {
        "keepWhitespace": false
      }
    }
  }
}

keepWhitespace : Hugo keeps white space by default. We have to set it to false to minimize white space on HTML

minimize002

Layout

layouts/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello Hugo</title>
  </head>
  <body>
    <div>Hello JAMstack</div>
  </body>
</html>

Create index.html in layouts folder.

minimize003

NPM Config

package.json

{
  "scripts": {
    "dev": "hugo server",
    "build": "hugo --minify"
  },
  "devDependencies": {
    "prettier": "^2.5.1"
  }
}

Line 2

"scripts": {
  "dev": "hugo server",
  "build": "hugo --minify"
}
  • dev : run web server under development mode
  • build : build HTML/CSS/JavaScript with minifier under production mode

minimize004

Development Mode

$ npm run dev

Start web server under development mode.

minimize005

Hugo runs successfully under development mode.

minimize006

HTML is not minimized under development mode.

minimize007

Production Mode

$ npm run build
$ serve public

Build HTML/CSS/JavaScript with minifier under production mode.

minimize008

Hugo runs successfully under production mode.

minimize009

HTML is minimized under production mode.

minimize010

Conclusion

  • Minimizing HTML is provided by Hugo. We don’t have to use other packages
  • Hugo keeps white space by default. We have to set keepWhitespace to false to minimize white space on HTML