Efficiently loading Angular modules using Webpack's lazy loading technique

I'm currently facing challenges while trying to implement lazy-loaded Angular modules with Webpack. Despite seeing the creation of a 1.bundle.js file containing the child app code, I am not observing any request for 1.bundle.js when loading the page, resulting in the failure of the child app initialization. The console.log statement never executes, and it seems that the module initialization by $oclazyload is not triggered at all.

Several aspects leave me perplexed:

1) Is it webpack's responsibility to send the request to the server, or do I need to manually load the second bundle? (Both approaches have been tried without success)

2) If manual loading of bundles is required, what should be the correct order of loading?

3) Despite attempting to control the bundle name via the third argument of require.ensure, the generated bundle always remains named 1.bundle.js regardless of the string passed.

4) Why does stepping through the code within the require.ensure block fail inside the debugger, leading to an undefined result shown in the Chrome source view?

(Code Below)

Main entry point code:

'use strict';

import angular from 'angular';
import 'angular-ui-router';
import 'oclazyload';


angular.module('parentApp', [
  'ui.router',
])
  .config(['$urlRouterProvider', '$locationProvider', ($urlRouterProvider, $locationProvider) => {
    $urlRouterProvider
      .otherwise('/');

    $locationProvider.html5Mode(true);
  }])

  .config(['$stateProvider', ($stateProvider) => {
    $stateProvider
      .state('child-app', {
        url: '/child-app',
        template: '<child-app></child-app>',
        resolve: {
          loadAppModule: ($q, $ocLazyLoad) => {
            return $q((resolve) => {
              require.ensure(['./child-app/app.js'], (require) => {
                let module = require('./child-app/app.js');
                console.log(module);
                $oclazyload.load({name: 'childApp'});
                resolve(module.controller);
              });
            })
          }
        },
        controller: function() {
        }
      })
  }]);

Child app:

'use strict';

import childAppTemplateURL from '../templates/child-app.html';
import childAppController from './controllers/childAppController';

export default angular.module('parentApp.childApp', [])

  .component('applicationListApp', {
      templateUrl: childAppTemplateURL,
      controller: childAppController
  });

Answer №1

The issue I encountered was not related to the require.ensure method. It seems to have been caused by an anomaly in how ocLazyLoad is packaged (https://github.com/ocombe/ocLazyLoad/issues/179). Resolving this problem was quite simple for me, as I just needed to add 'oc.lazyLoad' to the list of module dependencies.

angular.module('parentApp', [
  'ui.router',
  'oc.lazyLoad'
])

In response to my own queries, I discovered that Webpack indeed sends a request to the server for the bundle, and manual loading of the bundle is unnecessary. One thing that caught me off guard was that the resolve block fails silently if it includes a promise that cannot be resolved. In my scenario, the failure of $ocLazyLoad.load() went unnoticed, with the only hint being the absence of the

<child-app></child-app>
markup in the DOM, indicating that the state initialization did not occur.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the React state (array) to be empty within a callback function? Why is it failing to utilize the latest value from the external

I'm facing a challenge that has me stumped. I am attempting to add values to an existing array, but for some reason, the 'state' variable is always empty inside the onmessage callback function. I can't seem to figure out why this is hap ...

What is the best way to use jQuery to fill a dropdown menu with options from a JSON object?

Looking to populate a dropdown box #dropdown with values from a json object stored in a JavaScript string variable. How can I access each element as value/label pairs and insert them into the dropdown? The structure of the json string is as follows: [{"n ...

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

Is it possible to use a single function to both set the state and return JSX?

I'm currently grappling with creating a function that, when called, will update the state to an object {item: 'whatever the user types', list: [...list, todo]}. The challenge I'm facing is figuring out how to update the state and return ...

plugins: [ new webpack.LoaderOptionsPlugin({ // test: /.xxx$/, // can be used selectively for specific modules options: { modules: ... } }) ]

const webpack = require("webpack"); const path = require("path"); const DIST_DIR = path.resolve(__dirname, "dist"); const SRC_DIR = path.resolve(__dirname, "src"); const config = { entry: SRC_DIR + "/app/index.js", output: { path: DIST_DI ...

How can I remove a row from an MVC webgrid using an ajax call?

Within my MVC Razor view, I have a partial view containing webgrid data. My goal is to include an action link to delete a specific row of data. To accomplish this, I crafted the following JavaScript function: function delMeal(pid) { if (confirm("Do yo ...

Sharing AngularJS Controllers Across Multiple Pages

Is it possible to use the same controller across multiple pages in AngularJS? If so, how can you preload data from the server for each shared page differently? Can ng-init be utilized to address this challenge? ...

Issues with implementing ng-show and ng-disabled functions in AngularJS

I am currently working on a simple demo HTML page that involves client side form validation. My goal is to incorporate Bootstrap, AngularJS, and jQuery into this project, even though I am relatively new to AngularJS. However, I am facing some issues with ...

Retrieving Data Dynamically from a MEAN Stack Database Using Variables

I need to fetch data from MongoDB that matches a specific userId. Say I have the following data stored in the database: { "_id": "hjdhs88889dsijd8", "items": "xxxxxx", "userId": "A123" }, { "_id": "hjhuf77889dsijd8", "items": "xxxxxx", ...

Angular looping, split into multiple columns

I have a complex multi-checkbox form with up to 100 items in an array and a variable number of columns ranging from 1 to 5. For example, if I have 14 items and want to display them in 4 columns: []item 1 []item 5 []item 9 []item 13 []item 2 []item 6 ...

Which date picker is commonly recommended for use with AngularJS and Bootstrap?

When it comes to adding a date picker control in Angular/Bootstrap, there are a few options available. Is there one that stands out as the "better" choice? After some research, here is what I have discovered: HTML 5 input type of date: Support varies ac ...

Is there a method to adjust the styling of my <header> once the page hits a specific #anchor point?

Seeking some assistance with a website design challenge I am facing. I am currently working on a one-page portfolio site with four #anchor points that serve as "pages". Each div has a height of 100% to fill the entire browser height. The header, which co ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

JavaScript window.open not opening new window

Hey there, I'm currently working on logging into Twitter. Unfortunately, the window is not opening as expected in this code snippet. The response that is alerted isn't null and seems to be a link to a login screen. Any thoughts or suggestions on ...

Jade: Error Alert! Unexpected Identifier Detected on Ubuntu, whereas Mac Compatibility Confirmed

After successfully running this code on my Mac, I encountered an error when trying to migrate it to Ubuntu. Below is the index.jade partial that seems to be causing the issue: .container-fluid .row .jumbotron center h2 {{message}} ...

Loading image directories in AngularJS

Currently working on integrating an image gallery into my Angular application. Successfully managed to upload images in this post: File upload: create directory if it doesnt exist. The files are stored in subdirectories based on their project_id, and thi ...

Encountering issues with returning values correctly when using module.exports in Node.js

function userLogin(username, password) { var status; var userid = username; User.findOne({ 'username': [userid], 'password': [password] }, function(err, user) { if (!user) { console.lo ...

Recently embarked on my AngularJS learning journey

As a newbie in the world of AngularJS, I find myself facing a perplexing query. The confusion arises when deciding whether to employ {{ something here }} or simply {{ }}. Is there a secret technique in unraveling the instances where braces are indispensa ...

Error encountered: Google Maps API V3 is returning an undefined value for getCenter() function after an ajax call

Currently, I am in the process of updating search results through AJAX after dragging the map. The code snippet below illustrates how I am accomplishing this task: function initMap(){ var locations = []; var count = 0; $('.oneListing').each(func ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...