gohugoio / hugo

The world’s fastest framework for building websites.
https://gohugo.io
Apache License 2.0
73.49k stars 7.37k forks source link

unable to import netlify environment variable in assets/js/custom.js file #12586

Closed MittalShruti closed 2 weeks ago

MittalShruti commented 2 weeks ago

I am using this hugo theme flowbite-admin-dashboard. It uses webpack as well. This is how it builds the website:

"build": "NODE_ENV=production && run-s build:webpack build:hugo && rm /opt/build/repo/**/*.map",
"build:hugo": "hugo --destination=./public",
"build:webpack": "webpack --mode=production",
"build:styles": "npx tailwindcss -i ./src/style.css -o ./dist/css/flowbite.css",

My site is hosted on netlify. There I use npm run build in production.

I want to access environment variables (stored in netlify) in asset/js/custom.js file.

I tried adding this to layouts/_default/baseof.html file

  {{ $env := dict "encrypt" (getenv "HUGO_PARAMS_ENCRYPTION_KEY_HEX") }}
  {{ $js := resources.GetMatch "js/custom.js" | js.Build (dict "params" $env) }}
  <script async src="{{ $js.RelPermalink }}"></script>

in asset/js/custom.js file when i do import params from "@params" I get this error

custom.js:2 Uncaught Error: Cannot find module '@params'
    at webpackMissingModule (custom.js:2:50)
    at eval (custom.js:2:132)
    at ./assets/js/custom.js (app.bundle.js:19:1)
    at __webpack_require__ (bootstrap:19:1)
    at eval (index.js:11:78)
    at ./src/index.js (app.bundle.js:169:1)
    at __webpack_require__ (bootstrap:19:1)

I am new to hugo, how should i go about using env variables in .js file.

jmooring commented 2 weeks ago

Please use the forum (https://discourse.gohugo.io/) for questions and troubleshooting. We prefer to use GitHub for verified bugs and vetted enhancements. Thanks.