Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!