Search code examples
javascriptwebpackdynamic-import

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'));

Solution

  • 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.