How to include JS/CSS from node_modules folder in Hugo

In our previous posts:

we showed how to configure Hugo and your Theme to include custom JS/CSS file.

A usecase that is often relevant (especially considering EU GDPR laws) is to include Javascript and CSS not from a CDN, but include them locally from your site.

In practice, that means that we want to include it from the node_modules folder instead of, for example, jsDelivr.

In this example, we’ll include the katex library from the node_modules folder. It requires that you have configured Hugo to accept both custom CSS & custom Javascript as shown in the previous posts.

It requires that you have katex installed in your node_modules folder:

npm install --save katex

Hugo does not support including from the node_modules folder directly, so we need to symlink the files to the assets folder.

cd assets/js
ln -s ../../node_modules/katex/dist/katex.min.js katex.min.js

and, for the CSS

cd assets/css
ln -s ../../node_modules/katex/dist/katex.min.css katex.min.css

Now, in your hugo.yaml, you can include the files like this:

params:
  custom_css:
    - 'css/techoverflow.css'
    - 'css/kicad.css'
    - 'css/docsearch.css' # Algolia DocSearch library, symlinked from node_modules
    - 'css/katex.min.css' # KaTeX CSS, symlinked from node_modules
  custom_js:
    - 'js/kicad.js'
    - 'js/docsearch.js' # Algolia DocSearch library, symlinked from node_modules
    - 'js/algolia.js'
    - 'js/katex.min.js' # KaTeX JS, symlinked from node_modules

Important: This is not a post about how to configure KaTeX for Hugo (more steps are required for this!)! It’s just about how to include JS/CSS from the node_modules folder in Hugo.

Hugo will not automatically copy the assets from the assets folder to the public folder, so you need to make sure that your build process includes these files. This means you need to use resources.Get somewhere in your theme to include the files.

<link rel="stylesheet" href="{{ (resources.Get "css/katex.min.css").RelPermalink }}" />
<script defer src="{{ (resources.Get "js/katex.min.js").RelPermalink }}"></script>