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

Viewed 743

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

Yeah, this bit of webpack is weird. Truly dynamic import doesn't work. We can put string template inside the import statement, but putting variable name raises Dependency warning.

This is the closest I could achieve - put if conditions or switch case or a string template and then write the import in it.

Something like -

const getModule = (filename) => {return import(`directoryPath/${fileName}`);}

OR

const something = 'a.js';

if (something === 'a.js') {
  return import(`./${something}`); // promise
} else if (something === 'b.js'){
  .........
}

There's this thing with dynamic imports - webpack bundles all possible files in these conditions which is not cool.

Related