简体   繁体   English

如何从文件名变量导入javascript?

[英]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?是否可以从存储在运行时确定的变量中的文件名中导入 javascript,如下所示?

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 :如果你想在一个函数/模块中使用它,请注意它必须是一个异步函数,然后你就可以通过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.您可能需要使用外部工具才能在较旧的浏览器上运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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