Lazy-loading modules in SSR Angular 8 applications are currently unspecified

I am currently in the process of setting up my Angular 8 application to work with server-side rendering (SSR). However, I am encountering some undefined errors in webpack when running my application using ng serve, especially with lazy-loaded modules. Everything was functioning properly when I was using Angular 7, but after migrating to Angular 8, everything seems to be broken.

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'call' of undefined
TypeError: Cannot read property 'call' of undefined
    at __webpack_require__ (/Users/gwenaellarmet/Documents/Projects/ng-nouma/dist/server.js:137403:30)
    at Function.requireEnsure [as e] (/Users/gwenaellarmet/Documents/Projects/ng-nouma/dist/server.js:137422:25)
    at ɵ11 (/Users/gwenaellarmet/Documents/Projects/ng-nouma/dist/server.js:139660:6210)
    at RouterConfigLoader.loadModuleFactory (/Users/gwenaellarmet/Documents/Projects/ng-nouma/dist/server.js:232758:39)

I have made adjustments to both the tsconfig and angular.json configurations, but I keep encountering the same error consistently. I have disabled Ivy as it was also causing issues during the build process. While I suspect a connection between these problems, I cannot confirm it at this point, so my focus is on getting things to work without Ivy.

ERROR in src/app/pages/search/search.module.ts(68,12): error TS-991010: Value at position 12 in the NgModule.importss of SearchModule is not a reference: [object Object]
src/app/app.module.ts(41,12): error TS-991010: Value at position 6 in the NgModule.importss of AppModule is not a reference: [object Object]

tsconfig.json

... (omitted for brevity)

I am compiling my application using npm run build:ssr and serving it with npm run serve:ssr. My main goal is to ensure that all modules and markup are rendered with SSR for SEO purposes. Any assistance in pinpointing the root cause of these issues would be greatly appreciated.

Answer №1

One issue arises from having two copies of Angular in the traditional Universal setup, leading to confusion within the lazy loading system.

To resolve this problem manually, follow these steps:

Modify package.json

Add --bundleDependencies all at the end of the value for build:client-and-server-bundles

Adjust server.ts

Delete the following lines

import {enableProdMode} from '@angular/core';     
import {ngExpressEngine} from '@nguniversal/express-engine';  
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';
enableProdMode();
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

Then add

const {AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap} = require('./dist/server/main');

Update main.server.ts

Include

export {ngExpressEngine} from '@nguniversal/express-engine';
export {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';

Edit webpack.server.config.js

Insert

externals: {
 './dist/server/main': 'require("./server/main")'
}

For further details, check out: fix lazy loading and bundleDependencies

Answer №3

In short, I successfully got my project to work by simply removing the line enableProdMode(); from server.ts.


While this code was necessary for Angular 7, it seems that Angular 8 required some changes in the server.ts file.

  • To be safe, I created a backup file called server.bak.ts,
  • I then started a new blank project with SSR,
  • and finally copied the necessary code from the new project into the server.ts file.

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

Best Practices for Architecture and Routing in Angular 8 (suggestions)

As a newcomer to Angular, I find myself grappling with the recommended architecture for my project. In an effort to streamline my inquiry, I will structure it in the form of choosing between options A or B and exploring how to implement that choice. Specif ...

As I attempt to log in, the GitHub API is sending back a message stating that authentication

const fetchUser = async () =>{ let usernameValue : any = (document.getElementById('username') as HTMLInputElement).value; let passwordValue : any = (document.getElementById('password') as HTMLInputElement).value; const ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

Higher-Order Component integrated with HTMLElement

Check out this complex code snippet I created: export type AdvancedHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement> & { hoverDuration: number, onHoverChanged: (isHovering: boolean) => void }; export ...

Obtain information from a JSON file based on a specific field in Angular

The structure of the JSON file is as follows: localjson.json { "Product" :{ "data" : [ { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }, { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } ] ...

Bringing in a directive to a component in Angular

Can the Directive be imported into a Component without adding it to ngModule.declarations? I came across the CustomDirective for Telerik Angular Grid, which recommends using custom directives in the grid. However, I only need this directive in one compone ...

Guide on utilizing the maven-exec-plugin to execute npm clean commands

I am currently utilizing the exec-maven-plugin in my project. I have added extensions for npm install and npm clean commands. Below is the configuration section of the plugin in the pom file, which includes extensions for npm install, tsc run, and npm clea ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

What are the steps to resolve the error "Module parse failed: Unexpected character '�' (1:0)"?

I'm encountering an issue in my Js 13 app whenever I try to use a package related to images, specifically a blurhash package called blurhash-from-url. It keeps throwing an error. Error: ./node_modules/sharp/build/Release/sharp-darwin-x64.node Module p ...

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

What is the most efficient way to retrieve 10,000 pieces of data in a single client-side request without experiencing any lag

Whenever I retrieve more than 10 thousand rows of raw data from the Database in a single GET request, the response takes a significant amount of time to reach the client side. Is there a method to send this data in smaller chunks to the client side? When ...

Angular 5 - Empty array containing objects has a length of zero

In my app.component.ts file, I have an array initialized to load objects in the onInit event: ngOnInit() { this.pages = []; } Within the ngOnInit event, I also have a setInterval method that evaluates an expression every few milliseconds: setInterval(() ...

Utilize *ngIf to conceal a row within a material table

I'm struggling with hiding a row after clicking a button in the mat-table. I can't figure out where to place the *ngIf directive. I attempted using it on ng-container, but it didn't work as expected. Below is the excerpt from my HTML file. ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

When using RxJS forkjoin, it will cease subscription if there is a flatMap present within one of the observables it is awaiting

I have been experimenting with nested calls using rxjs and trying to implement nested forkJoins. However, I have encountered an issue where the outer forkJoin stops returning a result when there is a flatMap inside the inner observable. Here is a snippet ...

Top recommendations for steering clear of memory leaks in Angular

In my quest to identify and resolve potential memory leaks in my angular/spartacus application, I am currently focusing on locating any instances of "subscribe(..." calls within my code base for evaluation. I understand that the simplest solution is to us ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...