2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

await-loader — CommonJS-like async modules for webpack

Last updated at Posted at 2016-11-02

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.
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?