Home > Enterprise >  Cannot use import statement outside a module CLIENT-SIDE
Cannot use import statement outside a module CLIENT-SIDE

Time:05-19

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";;
});

CodePudding user response:

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();
});
  • Related