Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments:

angular.json

"architect": {
  "build": {
    ...
    "options": {
      ...
      "lazyModules": ["src/popup-components/popups.module"],
      ...
    }
  }
}

I included the module in the lazyModules section of the angular.json file to inform Angular to bundle it separately.

popups.module

import { NgModule } from '@angular/core';
...

@NgModule({
  imports: [CommonModule],
  declarations: [
    ...
  ],
  entryComponents: [
    ...
  ]
  ...
})
export default class PopupModule {}

app.component


@ViewChild('entry', { read: ViewContainerRef, static: true }) entry: ViewContainerRef

...

constructor(
  private _loader: NgModuleFactoryLoader,
  private _injector: Injector
) { } 

...

// takes the popup compenent to render as an argument
loadModule(popupComponent) {
  this._loader.load('src/popup-components/popups.module').then(moduleFactory => {
  const moduleRef = moduleFactory.create(this._injector).instance;
  const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(popupComponent);
  this.entry.createComponent(compFactory);
});
}

On running ng serve, everything works as expected without any errors. However, when I run ng build --prod, I encounter the following errors:

ERROR in ./src/popup-components/popups.module.ngfactory.js 58:64-79 "export 'PopupsModule' (imported as 'i1') was not found in './popups.module' ERROR in ./src/popup-components/popups.module.ngfactory.js 58:8885-8900 "export 'PopupsModule' (imported as 'i1') was not found in './popups.module' ERROR in ./src/popup-components/popups.module.ngfactory.js 58:8902-8917 "export 'PopupsModule' (imported as 'i1') was not found in './popups.module'

After reviewing the code in the popups.module, I noticed that I used export default class instead of the standard export default. Removing 'default' resolves the issue during production builds with ng build --prod, but it breaks dynamic loading of the module resulting in the error message when attempting to run the loadModule() method:

console.js:35 ERROR Error: Uncaught (in promise): Error: Cannot find 'default' in 'src/popup-components/popups.module'

At this point, I am unsure of the next steps to take as I have not come across any resources addressing this specific issue.

If anyone can offer assistance or guidance, it would be greatly appreciated!

Answer №1

Great news! I successfully resolved the issue by making the following changes:

Within my loadModule() function in the .load() section, I needed to adjust the code as shown below:

this._loader.load('src/popup-components/popups.module#PopupsModule)

This new syntax closely resembles the old way of lazy loading routing components (pre Angular 8) where the # symbol signifies the end of the file path and specifies the name of the PopupsModule.

In addition, I made a modification from:

const moduleRef = moduleFactory.create(this._injector).instance;

to:

const moduleRef = moduleFactory.create(this._injector);

After implementing these changes, the project now builds successfully using ng build --prod.

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

Option to modify the arguments of a method in a parent class

I encountered an interesting problem recently. I have two classes: class Animal { public talk() { console.log('...'); } } and class Dog extends Animal { public talk(noise: string) { console.log(noise); super.talk() } } The i ...

Guide on transforming an Angular 6 project into a Progressive Web Application (PWA)

Currently, my Angular 6 project is up and running smoothly. However, I am looking to integrate PWA into my existing application. When I execute the following command: ng add @angular/pwa The output displays: + @angular/<a href="/cdn-cgi/l/email-protec ...

Unlocking the power of localhost on your mobile device

Currently, I am working on a web application that utilizes Laravel for APIs and React for the frontend. My goal is to test this application on a mobile device. While testing React in isolation works fine, I am encountering issues with backend data such a ...

A Guide to Effectively Managing Express API Responses in Angular 2

When I make an Express API call from my Angular 2 application, I receive a response in the following way. In my component: this.emailService.sendEmail(this.name, this.email, this.message) .subscribe( (res) => ...

slider not functioning properly at the moment

I am in need of assistance with Fraction Slider from @jacksbox. I have read through the documentation multiple times, but I cannot seem to get my slider to display the effects it is meant to. The website I am working on can be found at . Here is an example ...

Angular 2 - One-Stop Form Component for Creating and Modifying

Seeking advice on how to efficiently reuse my Form Component. Data Model: class Contact { id?: String; name: String; } When a new Contact is created, the id is optional in the model as it doesn't exist at that point. When editing a Contac ...

creating a nested JavaScript object within another object

I need to create an object using the angular.forEach() function and then push another object while initializing all values to false. However, the current approach is causing errors. How can I achieve this correctly? Using "item.id" and "index.id" does not ...

"What is the method for verifying if a value is not a number in Angular 2

While attempting the following: dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}" An error is being thrown: browser_adapter.ts:82 ORIGINAL EXCEPTION: TypeError: self.context.isNaN is not a function Is there a way to determine ...

Refreshing Angular navigation directive post user authentication

As I delve into mastering AngularJS and embark on my inaugural "real" project, I find myself at a crossroads. Despite hours of scouring the internet in search of answers, I have yet to stumble upon a suitable solution that speaks to me in layman's ter ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

I am facing an issue with the routing functionality in the Quasar framework for Vue 3

I seem to be having an issue with my code where no matter what route I give, it only takes me to the home page. Specifically, when I give the path "auth", it still redirects me to the home page. Can someone please help me understand why this is happening a ...

Is there a method to implement retries for inconsistent tests with jest-puppeteer?

Currently, I am struggling with an issue where there is no built-in method to retry flaky tests in Jest. My tech stack includes Jest + TypeScript + Puppeteer. Has anyone else encountered this problem or have any suggestions for possible solutions? I attem ...

following the history.back() function call, the subsequent codes are executed

<?php $ok_register = 0; if($ok_register != 1) { ?> <javascript type="text/javascript"> alert("1"); history.back(); </javascript> <?php } ?> <javascript type="text/javas ...

Working with JSON data and extracting specific information within the grades

Here is a JSON data structure that contains information about a student named Alice and her grades in various courses: { "student": [{ "cert_id": "59826ffeaa6-b986fc04d9de", "batch_id": "b3d68a-402a-b205-6888934d9", "name": "Alice", "pro ...

Looking for assistance with troubleshooting my isotope.js [code written in jquery and html]?

Explore this JSFiddle link I'm attempting to create sortable fancybox images, similar to the filtering functionality seen on this website. I previously achieved this with v1 of isotope but have been struggling with v2. After countless attempts and ad ...

Is it possible to incorporate multiple searchBoxes on my website using the Google Maps API?

I am currently working on creating an origin and destination menu for users to select locations in each input. The goal is to add a marker to the map for each input and then calculate the distance between them. So far, I have successfully added a map with ...

Error: Unable to locate module: "./library". The parent module directory is "/"

I keep encountering an issue in my project when attempting to load a module. Whenever I try to import it from the node_modules folder, I receive the following error: Uncaught Error: Module not found: "./MyLibrary". Parent module folder was: "/" However, i ...

Tips for dynamically displaying images in both horizontal and vertical orientations

I would like to showcase images in the imageList. Here is what I want: AB CD How can this be achieved? It's not a matter of being even or odd Perhaps the list could look something like this: ABCDE FG I simply want a new row or display:block when ...

The reset function in React Native Controller FormData TextInput does not work properly

Encountering an Issue: While on the sensor overview page, I select a specific sensor and proceed to edit its name. Upon saving the changes and navigating back to the list of all sensors, I notice that the updated name has been successfully modified. Howeve ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...