0

Is it possible to import javascript from a filename stored in a variable to be determined at runtime, something like below?

const mydir="./bobs_pictures.js"
import pictures from mydir;
3

1 Answer 1

1

You can achieve that using dynamic imports, which run asynchronously.

const importPromise = import(mydir);
importPromise.then((module) => {
  // do something
});

If you want to use it across a function / module, note that it must be an async function, and then you'll be able to use it in a regular way with await:

async () => {
  const mydir = "./bobs_pictures.js";
  const module = await import(mydir);
}

PS. please check browser compatibility. You might need to use an external tool in order to run this on older browsers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.