3 ms·
Even though it is called "dynamic import", it still only accepts string literals as argument: import("module") // will work import(p) // will not work im
by linkdd 6y ago
Even 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