Dynamic Imports¶
This is an up-and-coming (ECMA2020) addition to the ECMAScript standard, so by the time being it's not usable in JavaScript natively, but it is in Meteor apps with their own custom implementation.
The dynamic import(...)
statement is a complementary method to the static import technique of requiring a module.
While a statically import
-ed module would be bundled into the initial JavaScript bundle, a dynamically import()
-ed module is fetched from the server at runtime, thus ensuring the optimization of the resources load.
Note that this would affect the active user experience as it will have to wait for the imported module to load, so some sort of <Loading ... />
component would be preferable in the process.
Usage¶
The import(...)
statement returns a Promise for the module namespace object of the requested module, that way the imported module can be fetched inside a Promise's then()
method.
import("tool").then(tool => tool.task());
Or inside an async function by await
ing the result without the need to provide a callback.
async function performTask() {
const tool = await import("tool");
tool.task();
}
Actual implementations¶
This was used in a bundle load refactor for the Hitcoins project, in which the router
component was importing all the React modules at once, instead of requiring them as the user accessed the pages that rendered them.
The full implementation can be viewed here.