An issue with including dynamically a JS file: how to do it correctly?

I can’t get jsFile3 to be included in the generated JS file.

This is what I’m doing:

  1. Getting the JS resources
  2. Creating an array of the JS resources I need to use on the page. $shouldHaveJsFile3 is a condition that is correctly true, let’s not focus on that.
  3. Concatening all these files into a single one.
{{-  1  -}}
{{- $jsFile1 := resources.Get "js/file1.js" -}}
{{- $jsFile2 := resources.Get "js/file2.js" -}}
{{- $jsFile3 := resources.Get "js/file3.js" -}}

{{-  2  -}}
{{- $shouldHaveJsFile3 := true -}}
{{- $allJsFiles := slice $jsFile1 $jsFile2 -}}
{{- if $shouldHaveJsFile3 -}}
  {{- $allJsFiles = $allJsFiles | append $jsFile3 -}}
{{- end -}}

{{-  3  -}}
{{- $jsResource := $allJsFiles | resources.Concat "js/main.js" -}}
{{- $jsFile := $jsResource | resources.Minify -}}
<script src="{{- $jsFile.Permalink -}}" defer></script>

When I print $allJsFiles, it contains the 3 JS files.
However, the generated $jsFile does not contain the $jsFile3, strangely… Here is the problem.

Could someone explain me what’s happening?
Thanks for your help.

I am unable to reproduce the problem. Try it:

git clone --single-branch -b hugo-forum-topic-40736 hugo-forum-topic-40736
cd hugo-forum-topic-40736
hugo server


Sorry for the late answer. I went a totally different route since I wasn’t able to make it work.

Your example works perfectly. In september, the more or less same code difn’t work for my website.

We can close the the topic, I guess. Thanks for your time.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.