Alain Jacomet Forte
Alain Jacomet Forte

Reputation: 4685

Lazy loading Angular directives in ui-router as Webpack chunks

I am trying to lazy load an Angular directive as a webpack chunk.

Here is my current config attempt at using ocLazyLoad:

// Basic Config
function routingBase( $urlRouterProvider, $locationProvider, $stateProvider ) { 

    $locationProvider.html5Mode(true);

    $stateProvider
        .state('home', {
            url: '/home',
            template: '<app-main></app-main>',
            resolve: {
                load: ( $q, $ocLazyLoad ) => {

                    let deferred = $q.defer(); 

                    require.ensure([], (require) => {

                        // Load entire module
                        let module = require('../modules/main');

                        $ocLazyLoad.load({ 
                            name: module.name 
                        });

                        deferred.resolve(module);

                    }, 'app-main');

                    return deferred.promise;
                }
            }
        })
}

This goes in myModule.config(routingBase);.

../modules/main is just an angular module that exports a directive (e.g. export default angular.module('main',[]).directive('appMain', appMainFn);.

Any tips? What I am getting is that the <app-main></app-main> is correctly added to the document, and that the chunk is correctly loaded as module. But it is not replaced (it stays as <app-main></app-main>).

Would you recommend a different method for lazy loading chunks (maybe using $compileProvider)? I would like the cleanest possible way.

Thank you very much for your help.

Upvotes: 0

Views: 546

Answers (1)

fernando
fernando

Reputation: 717

I was able to get this working in my current project. Just change the following line and see it works. You need to add default as well since you are exporting angular module as default. Cheers!

$ocLazyLoad.load({ 
name: module.default.name 
});

Upvotes: 0

Related Questions