Hi, everyone!
My issue is that on staging of the site imgs being built in js files are not shown due to incorrect src.
I have a project with structure of:
*assets
*js
*myfile.js
*static
*images
*someImg.svg
assets/js/myfiles.js creates an img and latter appends it to DOM:
...
let img = document.createElement("img");
img.src = "/images/someImg.svg"
...
Scipts are added to the document in head.html file:
{{ $myFileList := resources.Get "js/myfile.js" | minify | fingerprint }}
<script type="text/javascript" src="{{ $myFileList.RelPermalink }}" defer></script>
head.html is added to baseof.html:
<head>
{{ partial "head_homepage" . }}
</head>
config.toml has baseURL = "/"
.
package.json structure:
"scripts": {
"build_code_samples": "./build_code_samples.sh",
"develop": "cd site && hugo server",
"build": "cross-env HUGO_ENV=production hugo --minify -d ../dist -s site -v",
"start": "hugo -d ../dist -s site -vw"
},
I have an issue of /images/someImg not being shown on staging (localhost and prod are fine). It happens because staging have an url structure like: siteStaging/21984/ (where 21984 is PR number, so it’s always different). Everything works fine on localhost and prod, since there path doesn’t have any additional slashes with numbers. So my src calculates like “siteStaging/images/someImg.svg” insatead of "siteStaging/21984/images/someImg.svg. If i manually add /2194/ imgs are shown.
After some examination I came to conslusion that I should:
- make js file to be included in hugo, so I changed head.html:
{{ $myFileList := resources.Get "js/myfile.js" | resources.ExecuteAsTemplate "js/myfile.js" . | minify | fingerprint }}
<script type="text/javascript" src="{{ $myFileList.RelPermalink }}" defer></script>
- change js files themselves so the would pick up any URL by using relURL, but I can’t figure out what syntaxis should I use. I tried different variants, but none of them worked:
img.src = "{{ /images/arrow-expandable.svg | relURL }}"
or
img.src = {{ "/images/arrow-expandable.svg" | relURL }}
or
img.src = "{{ "/images/arrow-expandable.svg" | relURL }}""
So the questions are:
- Is my approach correct at all?
- If yes, what is the correct syntaxis of doing it?