Home > Mobile >  JavaScript import does not work in a different or same file
JavaScript import does not work in a different or same file

Time:02-20

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

CodePudding user response:

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>

CodePudding user response:

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

  • Related