Aurelia 2 bundling portions of application

Aurelia 2 doesn’t have runtime magic, this simplified lots of implementation. For dynamic loading, Aurelia 2 relies on standard ESM feature: dynamic import().

In Aurelia 2, To use a resource (custom element, or route component), the code needs to explicitly import that resource.

In js/ts

import {SomeResource} from './some-resource';
// Then use SomeResource directly in code

In html

<import from="./some-resource"></import>

You can write <require from... too, require and import tags are same in Aurelia 2.
The Aurelia 2 conventions is implemented as a bundler plugin (for webpack, it’s @aurelia/webpack-loader), the plugin translates html into js code, the above import tag is translated into

import * as d0 from './some-resource';
// Then d0 is used as a dependency of this custom element

This is very different from Aurelia 1, where Aurelia 1 deals with <require> tag at runtime. Aurelia 2 does it at compile time.

So, there is no magic to accept a module id string as a resource in Aurelia 2, it’s all translated into static import.

In Aurelia 1, PLATFORM.moduleName is introduced as a hint for webpack to pick up the module id string, in order to bring in dependency.

In Aurelia 1, module id string gave Aurelia the flexibility to lazy load a resource. It only starts to request the resource module when it’s firstly used in the app UI. Whether it’s in currently loaded js bundle (or call chunk), or additional bundle to be loaded, it doesn’t matter.

In Aurelia 2, most resources are loaded statically, so you lose the default lazy load behaviour in Aurelia 1. In some use case you do need lazy loading, for example a route component, Aurelia 2 allows you to supply a promise, normally implemented with dynamic import().

() => import('./another-route')

This is a pattern you probably have seen in many other frameworks’ router.

I am pretty sure the new router in Aurelia 2 supports lazy loading, but I have not tried it. @jwx probably can provide you a better example.

When you use dynamic import() to lazy load a module, some bundlers provide automatic code splitting, some may require little config. You can refer to bundler document for the details.

5 Likes