Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda