3 ms·
As far as I know, ES modules do not allow variables as module name: const moduleName = "foo" import something from moduleName // will not work const some
by linkdd 6y ago
As far as I know, ES modules do not allow variables as module name:
const moduleName = "foo"
import something from moduleName // will not work
const something = await import(moduleName) // will not work
I'm genuinely curious about how someone would do this with ES modules:
// somewhere in a function or a class method
const plugins = pluginModules.map(require)
EDIT: I was wrong, the import() function does work with variables.
- epidemian 6y agoI'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
- eyelidlessness 6y agoMinor nitpick but it’s actually an important distinction: `import` isn’t technically a function, it’s a different kind of syntax that looks like a function. It’s not a value you can pass as a callback, for example. And this is good, in a way, because it allows for all sorts of static optimization that would otherwise make large scale ESM usage trivially pathological.