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

181
Views
Cannot use import statement outside a module CLIENT-SIDE

At client-side, I want to import only a specific part of my Javascript module. But I wanna do that on demand, like when a user performs an action that needs that specific part of the module. I was able to accomplish that in the HTML file, with:

<script type="module">
 import { sayHi } from "/public/js/sayHi.js";
 sayHi("John");
</script>

Now I want to do the same but in my client-side JS file, so that I run this loading whenever I want (and not on page load, as in the example above). The closest that I got from solving it was running this in my client-side JS file:

import("/public/js/sayHi.js")

But the problem is that this last script loads the whole module, not just the part that I want. If I try to do this:

import { sayHi } from "./sayHi.js";

I get the error "Cannot use import statement outside a module".

How can I import only the { sayHi } part via my client-side JS?

P.S.: Just to give an example, I would like to have something like that in my client-side JS:

buttonX.addEventListener('click', async () => {
  const a = await import { sayHi } from "./sayHi.js";;
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It loads the whole module, not just the part that I want

It always does, you cannot avoid that. This also happens when you use import {…} from '…' - it just doesn't import everything into the current module scope. Just like when you call import(…), you don't have to use all available parts:

buttonX.addEventListener('click', async () => {
  const { sayHi: a } = await import("./sayHi.js");
  a();
});
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!