Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
How to make JavaScript variables available to ES6 modules

Say I have a website with a file structure like this:

index.html
main.js
modules/my-module.js

index.html contains (along with a lot of HTML):

<button id='my-btn'>My Button</button>
<script type='module' src='./main.js'></script>

main.js contains:

import { myBtn } from "./modules/my-module.js";

and modules/my-module.js contains:

const myBtn = document.querySelector("#my-btn");
myBtn.addEventListener("click", function(){
    alert("Hallo from My Button");
});
export { myBtn };

Now if I click on the button I get an alert as expected.

The problem I am having is that I have some information (ie variables with values such as strings, arrays etc) in other script tags on the index.html page which I need in modules/my-module.js

I do not want to use a global variable for this because they are evil.

I thought of creating an element(s) on the index.html page with data set attributes as keys and assign values to them. The element could then be accessed from modules/my-module.js and its data set attributes would be readable. This does work when I try it but it seems a long winded way of getting access to information available on the index.html page.

It has been suggested I create a class or function returned by the module and pass data into it. The problem with that, to me, is that I am trying to keep code related to the same thing all together in the same module. If I have to pass functions out of the module to be invoked with extra data then my code base is less well organised.

Is there any other approach which would be more direct?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!