Can I dynamically import an ES6 module?

Viewed 69

I'm trying to have subcommands in my program, but I want to have them in a list and import them all at once. Can I do something like this:

const subcommands = ['help', 'add', 'remove'];
for (const subcommand of subcommands) {
  import {main} from './'+subcommand+'.js';
  main();
}
2 Answers

Yes there is an function for dynamic imports. mdnimport().
It returns a promise so you can put a then after it, or use async await.

(async () => {
  const subcommands = ['help', 'add', 'remove'];
  for (const subcommand of subcommands) {
    const {main} = await import('./'+subcommand+'.js');
    main();
  }
})()

You can use the dynamic-import function.

const subcommands = ['help', 'add', 'remove'];
for (const subcommand of subcommands) {
  import('./'+subcommand+'.js').then(i => {
     i.main()
  })
}
Related