5 ms·
I'm not entirely sure since i've never done this, but i think you can use the dynamic import() function[1] and await all the import promises: const plugins =
by epidemian 6y ago
I'm not entirely sure since i've never done this, but i think you can use the dynamic import() function[1] and await all the import promises:
const plugins = await Promise.all(pluginModules.map(p => import(p)))
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- linkdd 6y agoEven though it is called "dynamic import", it still only accepts string literals as argument: import("module") // will work import(p) // will not work import(`${p}`) // will not work
- realityking 6y agoThis works just fine in Node.js 14.15: // test2.mjs console.log("works!"); // test.mjs const m = "./test2.mjs"; import(m)
- epidemian 6y agoThere's an `import` statement with its custom syntax, which yes, does not allow anything else than a static string literal on the `from` part. But there's also an import() function, which is, well, just a function, so you can pass to it whatever parameter you want. For example a string computed dynamically as in your example. The linked page in my comment has a couple of examples of that function.
- rich_harris 6y agoI think you're thinking of module bundlers, which need to be able to resolve the import statically in order to do code-splitting etc. There's no such limitation at runtime.
- eyelidlessness 6y agoEven so they do tend to have facilities for dynamic imports of that kind, but it’s generally bad for bundle size and should be used sparingly.
- kall 6y agothat’s just a limitation of webpack