TL;DR
Module loading nirvana for webpack: await-loader.
const myModule = await require('await!my-module');
Rationale
Loading modules in CommonJS manner is graceful, but slows down application loading time due to all modules are built into single huge bundle. On the other side, when you use AMD, you can speed up load time, but you risk to get too complicated and terrible code.
Existing solutions (for webpack)
promise-loader
Using this loader, you can asynchronously load modules like this:
// TypeScript/ES7
const loadMyModule = require('promise?bluebird!my-module');
const myModule = await loadMyModule();
// Do what you want.
or this:
// ES6
var loadMyModule = require('promise?bluebird!my-module');
loadMyModule().then(function (myModule) {
// Do what you want.
});
As you can see, this loader doesn't return loaded module immediately, instead you have to initiate loading manually, and then — do what you want with resolved promise. Also, it requires you to specify promise library of your choice; even if you are using native promises or already loaded promise library, you must specify promise library as global
.
My solution
Simple as this:
// TypeScript/ES7
const myModule = await require('await!my-module');
// Do what you want!
Pros:
- Modules are loaded asynchronously,
- but without the pain and mess.
- Doesn't require any configuration in loader's query string.