Extend Hugo with JavaScript and CSS

Posted on October 11, 2023 • 2 min read • 338 words

How do I add my own JavaScripts (JS) and Cascading Style Sheets (CSS) to Hugo?

Extend Hugo with JavaScript and CSS
Photo by freepik  on Freepik 

Barely has the Hugo website been up and running when new desires arise to extend the functionality and presentation beyond the template options. Perhaps other people besides me have stumbled over how to embed these files in the existing Hugo infrastructure. So here is my approach.

JavaScript files are generally static files and are saved within the Hugo project in static/js. The same applies to style sheet files, which are stored in the static/css folder.

As you never know exactly how many such scripts will be added over time, I have chosen to use simple lists to keep the complexity manageable.

To do this, you create a list of all the JS and CSS files to be added in the configuration file params.toml.

[main]
    customJS = ["js/tool.js", "js/feature.js"]
    customCSS = ["css/border.css"]

As the new functions are expected to be available on all generated pages, they are integrated via the header, which is often defined in Hugo in the file layouts/partials/head/head.html. To do this, add the lines for js and css at the end of the file.

{{ define "head" }}

    [... header functions from template ...]

    <!-- js -->
    {{ range site.Params.main.customJS -}}
        <link type="text/js" rel="stylesheet" href="{{ . | absURL }}">
    {{- end }}
    <!-- css -->
    {{ range site.Params.main.customCSS -}}
        <link type="text/css" rel="stylesheet" href="{{ . | absURL }}">
    {{- end }}
{{ end }}

With the help of a for loop over all elements of the customJS or customCSS lists, html code is generated to include the files.

After restarting the Hugo server or regenerating the static website, the relevant part in <head> ... </head> section of a page looks something like this:

<!doctype html>
<html lang="de">
[...]
    </head>
[...]
        <link type="text/js" rel="stylesheet" href="http://<MeineDomain/js/tool.js">
        <link type="text/js" rel="stylesheet" href="http://<MeineDomain/js/feature.js">
        <link type="text/css" rel="stylesheet" href="http://<MeineDomain/css/border.css">
    </head>
[...]
</html>

Résumé

With help of general lists of the JavaScript and style sheet files to be added in the central params.toml file of the Hugo configuration and a bit of coding, you can integrate your own script files into every page of a Hugo project.