Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda