Note: Dynamic imports require Meteor 1.5 or higher.
The dynamic-import package provides an implementation of
Module.prototype.dynamicImport, an extension of the module runtime which
powers the dynamic import(...)
statement, an up-and-coming (currently stage 3 out of 4) addition to the
ECMAScript standard.
The dynamic import(...) statement is a complimentary method to the static
import technique of requiring a module. While a statically import-ed
import()-ed
Once a module is fetched dynamically from the server, it is cached permanently on the client and additional requests for the same version of the module will not incur the round-trip request to the server. If the module is changed then a fresh copy will always be retrieved from the server.
Usage
The import(...) statement returns a Promise
which is resolved with the exports of the module when it has been successfully
fetched from the server and is ready to be used.
Because it’s a Promise, there are a couple methods developers can use to
dictate what will happen upon the availability of the dynamically loaded module:
The .then() method of the Promise
1 | import("tool").then(tool => tool.task()); |
By await-ing in an asynchronous function
Meteor supports async and await,
which provide a straightforward approach to asynchronously wait for the
module to be ready without the need to provide a callback:
1 | async function performTask() { |
Default exports
The
import(...)Promiseis resolved with theexportsof the module. If it’s necessary to use the “default” export from a module, it will be available on thedefaultproperty of the resulting object. In the above examples, this means it will be available astool.default. It can be helpful to use parameter de-structuring to provide additional clarity:
1 import("another-tool").then(({ default: thatTool }) => thatTool.go());