Reputation:
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
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
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