Bundling JavaScript Files

When you built the search for your site, you used JavaScript libraries hosted on a CDN. This requires your browser to make additional requests to fetch those libraries. Hugo can combine all of your scripts into a single minified file, and you can fingerprint the file just like you did with your stylesheets. Sometimes this is preferable, as you’ll have all your project’s dependencies under your control.

To make this work, first move the js folder from the static directory of your site to the assets directory, just like you’ve done with stylesheets. You can do this in your editor, or from the command-line interface like this:

 $ ​​mv​​ ​​themes/basic/static/js​​ ​​themes/basic/assets/js

Then, download Lunr and Axios and place them in the assets/js directory, but be sure to grab the full unminified versions. You can use the curl command-line tool to download these files or visit the URLs in your browser and save the files that way:

 $ ​​cd​​ ​​themes/basic/assets/js
 $ ​​curl​​ ​​https://unpkg.com/lunr@2.3.6/lunr.js​​ ​​>​​ ​​lunr.js
 $ ​​curl​​ ​​https://unpkg.com/axios@0.19.0/dist/axios.js​​ ​​>​​ ​​axios.js
 $ ​​cd​​ ​​-

You’ll also find these files in the assets/portfolio/themes/basic/assets directory of the book’s companion files.

Open themes/basic/layouts/_default/search.html and remove the existing script tags. Replace them with these lines that load Lunr, Axios, and your search.js file:

 {{ $lunr := resources.Get "js/lunr.js" }}
 {{ $axios := resources.Get "js/axios.js" }}
 {{ $search := resources.Get "js/search.js" }}

The resources.Concat function takes a list of resources (known as a Slice in Go) and combines them into the file you specify. Add these lines to concatenate, minify, and fingerprint the output file:

 {{ $libs := slice $lunr $axios $search }}
 {{ $js := $libs | resources.Concat "js/app.js" | minify | fingerprint }}
 <script src=​"{{ $js.RelPermalink }}"​></script>

Save the file and restart your Hugo server. Revisit your search page at http://localhost:1313/search and ensure it still works.

Hugo’s asset pipeline is a fantastic feature, and you can get pretty far with it, but front-end development can get a lot more complex than concatenation and minification. You’ll likely want to use more complex JavaScript build processes for those casses.