Search code examples
javascriptwebpackbundling-and-minification

How are modules loaded dynamically if there is only a single bundled JavaScript file?


I know when using a module loader like webpack the resulting output will be a single JavaScript file like bundle.js. Now in index.html I only need to reference the following:

<script src="bundle.js"></script>

My question is, if I have a single .js file, how does dynamic module loading occur? Maybe I'm way off here in my understanding, but isn't the whole idea of a module loader to not server a module .js file until it is needed? Hence not having to load all files from the start of the app and index.html. Well if I have already served up that single bundle.js file from index.html, how are the separate modules within that file served up async and only as needed? At that point I feel I've already taken the hit for downloading the file, so the performance part is not gained.

How do the module loaders work when only a single bundled .js file is served for the entire app?


Solution

  • When you use Webpack this way you're not using any module loaders or dynamic loading. Webpack is a module bundler which means it resolves all the required modules, combines them into a single file and allows you to include that in your web page (or wherever you want to use the code).

    If you were working in an environment where module loading was supported, you wouldn't even need Webpack (not going into minifying, transpiling or polyfilling here). You would just use module loading and that's it.