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

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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