简体   繁体   中英

How to import javascript from filename variable?

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM