Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a truly dynamic import() in webpack?

I've been trying to use the import() function to import something which is dynamic at runtime. I would think that as long as I create an entry for the file, webpack could be smart enough to import() the correct module, but that doesn't seem to be the case.

Does anyone know of a way to chunk off an entry and use the import() syntax, feeding it a variable, and have it work at runtime?

A simple example of the root problem is as follows:

// works
import( './a.js' ).then(() => console.log('it worked'));

// something is a dynamic variable that changes at runtime
const something = './a.js';
// does not work, even with this simplistic example
import( something ).catch(() => console.log('it did not work'));
like image 912
jas7457 Avatar asked Nov 19 '25 02:11

jas7457


1 Answers

It does not work because, although it is called "dynamic import" it is does not follow what the word means. The idea on "dynamic" import is to be able to import something dynamically at runtime, but here it is caveat: the module to be imported has to be known.

Since webpack does static analysis to do the lazy loading on these import() statements, everything has to be known and predictable, otherwise webpack would not be able to create async chunks on the fly. That is why adding a variable to the import does not work.

like image 200
PlayMa256 Avatar answered Nov 20 '25 15:11

PlayMa256



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!