Home > OS >  Can I dynamically import an ES6 module?
Can I dynamically import an ES6 module?

Time:08-11

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

CodePudding user response:

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

CodePudding user response:

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