user19738252
user19738252

Reputation:

Can I dynamically import an ES6 module?

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();
}

Upvotes: 4

Views: 2148

Answers (2)

BergerAPI
BergerAPI

Reputation: 64

You can use the dynamic-import function.

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

Upvotes: 2

science fun
science fun

Reputation: 411

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();
  }
})()

Upvotes: 3

Related Questions