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

387
Visualizações
How to send a data to one Javascript script file to another Javascript script file

I want to send a = 5 to another js file and add them,the other file should have a type = "module" in it.

<script>
  let a = 5;
  // file 1
</script>
    
<script type="module">
  console.log(a+5)
  // file 2
  // I need (type = "module") in file 2
</script>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because modules run and load asynchronously, the non-module script will run first, which will make things a bit difficult. I'd put the non-module script in a separate file - this will allow you to use the defer attribute on its script tag (defer has no effect on inline scripts). Since deferred scripts run in the order in which they appear in the DOM, you can then have the module expose something globally, first, and then have the deferred non-module call that global function.

<script src="file-2.js" type="module"></script>
<script defer src="file-1.js"></script>
// file-2.js
window.doSomethingWithA = (a) => {
  console.log(a);
}
// file-1.js
window.doSomethingWithA(5);

But a better approach would be to put all your scripts into modules - it'll make things a lot easier to manage when the code becomes of any reasonable size. It's also counter-productive for a module to make something global - one of the big selling points of modules is that they can be made to be completely self-contained.

Another approach, without relying on script order, would be to have the non-module script listen for a load event on the module script, then call the global function.

about 4 years ago · Juan Pablo Isaza Relatório

0

For this answer assume both the files are in the same folder:

Folder
   |- firstFile.js
   |- secondFile.js

add export in firstFile.js

//firstFile.js
export let a = 5;

and import in secondFile.js

//secondFile.js
import {a} from './firstFile.js'
console.log(a)

result:
5
about 4 years ago · Juan Pablo Isaza Relatório
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