0

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";; }); 
3
  • 1
    Importing anything from a module will always load the whole file/module. If you use a dynamic import then you get an object back whose properties are the module exports. So you would access e.g. (await import("/public/js/sayHi.js")).sayHi. Commented May 18, 2022 at 23:02
  • 1
    Not possible. From the documentation... "Use dynamic import only when necessary. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and tree shaking." Commented May 18, 2022 at 23:03
  • 2
    Loading/using only part of the file is something some bundlers can do ("tree shaking") but that's a specific feature of those bundlers and works via static analysis, not at runtime. Commented May 18, 2022 at 23:03

1 Answer 1

2

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(); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.