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

148
Visualizações
JavaScript import does not work in a different or same file

If I import something, then use it, it will not work in a function or without a function for external js but with inline js

for example

<html>
<body>
<button onclick="foo()">Click Me</button>
</body>
<script type="module">
import confetti from 'https://cdn.skypack.dev/canvas-confetti';
confetti()
</script>
</html>

works

but

<html>
<body>
<button onclick="foo()">Click Me</button>
</body>
<script type="module">
import confetti from 'https://cdn.skypack.dev/canvas-confetti';
function foo(){
confetti()
}
</script>
</html>

and

<html>
<body>
<button onclick="foo()">Click Me</button>
</body>
<script type="module" src="script.js"></script>
</html>

script.js:

    import confetti from 'https://cdn.skypack.dev/canvas-confetti';
    function foo() {
        confetti()
    }

or script.js:

    import confetti from 'https://cdn.skypack.dev/canvas-confetti';
        confetti()
    

don't work

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Please stop using inline event listeners, which requires global variables and thus defeats the whole purpose of modules.

Instead, use JavaScript to add the listener:

<button id="foo">Click Me</button>
<script type="module">
  import confetti from 'https://cdn.skypack.dev/canvas-confetti';
  document.getElementById('foo').addEventListener('click', confetti);
</script>
about 4 years ago · Juan Pablo Isaza Relatório

0

the problem is with defining the type of the script as module, the type module means that you want to import another module in this script. so the variables and function inside the script of the type module are not accessible outside the scope of execution.

the solution is to assign the function to the global scope window scope:

<script type="module">
  import confetti from "https://cdn.skypack.dev/canvas-confetti";
  window.foo = function () {
    confetti();
  };
</script>

here is a live demo

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