How to import environment variable in html and js files

I have a index.html which has this line:

<button type="button" id = "bButton " onclick="location.href='https://myserver-dev.com/Builder/builder.html'">Builder</button>

And I have another JS file builder.js where I am setting env variable like this:

//  var envURL = "http://localhost:8080";
  var envURL = "https://myserver-dev.com";
  //var envURL = "https://myserver-test.com";

I was thinking of creating a separate JS file, maybe something like properties.js or env.js and put the following in it:

//  var envURL = "http://localhost:8080";
  var envURL = "https://myserver-dev.com";
  //var envURL = "https://myserver-test.com";

If I do that what would be the best way to get the envURL inside index.html and builder.js at appropriate places?

For importing into HTML, just use the script tag. For js files importing other js files use the export and import statements. You can see an example of how to use these here…

https://www.tutorialrepublic.com/faq/how-to-include-a-javascript-file-in-another-javascript-file.php

Thank you @Martyr2 . What I did was, I included the properties.js file containing all global variables in index.html using <script> tag and used it like the following:

location.href = envUrl + '/Builder/builder.html';

I included properties.js in builder.html using <script> tag and then I didn’t need to import it in builder.js and I could just use envURL in my builder.js file.

Cool. I would still advise you to take a look at the import/export statements and understand them. Including all files into the HTML directly can work, but there will be times where you will want/need to import directly to the JS files. There is a reason that the import/export statements were created. :wink:

Sure, I will. Thanks again!

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