mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-23 01:58:29 +00:00
Demonstrate lazy-loading for Webpack-bundled KO components
This commit is contained in:
25
templates/KnockoutSpa/ClientApp/webpack-component-loader.ts
Normal file
25
templates/KnockoutSpa/ClientApp/webpack-component-loader.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import * as ko from 'knockout';
|
||||
|
||||
// This Knockout component loader integrates with Webpack's lazy-loaded bundle feature.
|
||||
// Having this means you can optionally declare components as follows:
|
||||
// ko.components.register('my-component', require('bundle?lazy!../some-path-to-a-js-or-ts-module'));
|
||||
// ... and then it will be loaded on demand instead of being loaded up front.
|
||||
ko.components.loaders.unshift({
|
||||
loadComponent: (name, componentConfig, callback) => {
|
||||
if (typeof componentConfig === 'function') {
|
||||
// It's a lazy-loaded Webpack bundle
|
||||
(componentConfig as any)(loadedModule => {
|
||||
// Handle TypeScript-style default exports
|
||||
if (loadedModule.__esModule && loadedModule.default) {
|
||||
loadedModule = loadedModule.default;
|
||||
}
|
||||
|
||||
// Pass the loaded module to KO's default loader
|
||||
ko.components.defaultLoader.loadComponent(name, loadedModule, callback);
|
||||
});
|
||||
} else {
|
||||
// It's something else - let another component loader handle it
|
||||
callback(null);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user