angular / angular-cli

CLI tool for Angular
https://cli.angular.io
MIT License
26.74k stars 11.98k forks source link

Angular SSR Migration Bug #27948

Closed msalq closed 2 months ago

msalq commented 3 months ago

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

I encountered an error while upgrading my Angular application from version 14 to version 18. Specifically, during the migration from Angular 16 to 17, Angular Universal was migrated to SSR, which led to changes in the server.ts file. Despite ensuring there are no circular imports, I am unable to resolve the error.

My server.ts file

import "zone.js/node";
import * as express from "express";

import { APP_BASE_HREF } from "@angular/common";
import { CommonEngine } from "@angular/ssr";

import { existsSync } from "node:fs";
import { join } from "node:path";

import bootstrap from "./src/main.server";

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), "dist/dummy-app-name/browser");
  const indexHtml = existsSync(join(distFolder, "index.original.html"))
    ? "index.original.html"
    : "index";

  const commonEngine = new CommonEngine();

  server.set("view engine", "html");
  server.set("views", distFolder);

  // Serve static files from /browser
  server.get(
    "*.*",
    express.static(distFolder, {
      maxAge: "1y",
      index: "index.html",
    })
  );

  // All regular routes use the Angular engine
  server.get("*", (req, res, next) => {
    const { protocol, originalUrl, baseUrl, headers } = req;

    commonEngine
      .render({
        bootstrap,
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: distFolder,
        providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
      })
      .then((html) => res.send(html))
      .catch((err) => next(err));
  });

  return server;
}

function run(): void {
  const port = 8080;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

run();

My app.server.ts file

import { enableProdMode } from "@angular/core";

import { environment } from "./environments/environment";

if (environment.production) {
  enableProdMode();
}

export { AppServerModule as default } from "./app/app.server.module";
export { renderModule } from "@angular/platform-server";

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

return value.ngModule !== undefined;
               ^

TypeError: Cannot read properties of undefined (reading 'ngModule')
    at isModuleWithProviders (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/vendor.js:181640:16)
    at maybeUnwrapModuleWithProviders (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/vendor.js:193659:10)
    at Array.map (<anonymous>)
    at convertToTypeArray (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/vendor.js:193655:26)
    at Object.toString (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/vendor.js:193637:32)
    at noSideEffects (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/vendor.js:165871:5)
    at Module.ɵɵsetNgModuleScope (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/vendor.js:193635:10)
    at /Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/main.js:27636:57
    at 26800 (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/main.js:27641:3)
    at __webpack_require__ (/Users/username/Desktop/Work/dummyappname.io/repos/ws-web/dist/dummyappname/server/main.js:28715:42)

Please provide the environment you discovered this bug in (run ng version)

_                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 18.0.4
Node: 18.19.0
Package Manager: npm 10.2.3
OS: darwin arm64

Angular: 18.0.3
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, platform-server
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1800.4
@angular-devkit/build-angular   18.0.4
@angular-devkit/core            18.0.4
@angular-devkit/schematics      18.0.4
@angular/cdk                    16.2.14
@angular/cli                    18.0.4
@angular/flex-layout            14.0.0-beta.41
@angular/google-maps            16.2.8
@angular/material               16.2.14
@angular/ssr                    18.0.4
@schematics/angular             18.0.4
rxjs                            7.5.7
typescript                      5.4.5
zone.js                         0.14.7

Anything else?

No response

alan-agius4 commented 3 months ago

This seems like a bug but we'll need to look at a reproduction to find and fix the problem. Can you setup a minimal repro please?

You can read here why this is needed. A good way to make a minimal repro is to create a new app via ng new repro-app and adding the minimum possible code to show the problem. Then you can push this repository to github and link it here.

This might be related to your directory structure so its really important to get an accurate repro to diagnose this.

msalq commented 3 months ago

@alan-agius4 I think creating a repro with the exact same message might be really hard to come up with. As our application is a very complex and large scale application. However I tried something and Im getting an error that is similar to the error seen in my main application.

Heres the link to the repro: https://github.com/msalq/Angular-SSR-Migration-Bug-Repro

The error I get when ssr serving is "Module not found" which I think is stemming from the same RCA as my main application, just surfacing under a different format.

alan-agius4 commented 2 months ago

@msalq, I downloaded the reproduction, but I am not getting any error

alanagius@alanagius-linux  ~/Angular-SSR-Migration-Bug-Repro   main  ng b --no-prerender
Browser bundles        
Initial chunk files     | Names               |  Raw size | Estimated transfer size
main-UJVQOKDB.js        | main                | 216.14 kB |                59.08 kB
polyfills-6EAL64PA.js   | polyfills           |  34.23 kB |                11.13 kB
styles-5INURTSO.css     | styles              |   0 bytes |                 0 bytes

                        | Initial total       | 250.38 kB |                70.21 kB

Server bundles         
Initial chunk files     | Names               |  Raw size
server.mjs              | server              |   1.11 MB |                        
chunk-4XE7LDMD.mjs      | -                   | 459.97 kB |                        
polyfills.server.mjs    | polyfills.server    | 268.32 kB |                        
chunk-SWJQVCSS.mjs      | -                   |  24.42 kB |                        
chunk-44X6ELFP.mjs      | -                   |   1.63 kB |                        
render-utils.server.mjs | render-utils.server | 219 bytes |                        
main.server.mjs         | main.server         | 184 bytes |                        

Lazy chunk files        | Names               |  Raw size
chunk-TUONMDNT.mjs      | xhr2                |  12.08 kB |                        

Output location: /Angular-SSR-Migration-Bug-Repro/dist/tes

Application bundle generation complete. [4.175 seconds]

 alanagius@alanagius-linux  ~/Angular-SSR-Migration-Bug-Repro   main  node /Angular-SSR-Migration-Bug-Repro/dist/tes/server/server.mjs 
Node Express server listening on http://localhost:4000
msalq commented 2 months ago

can you run these commands:

ng build npm run serve:ssr:tes

the bug might go away with the no-prerender tag

msalq commented 2 months ago

also, I just want to highlight how everything was working fine with angular universal, its with ssr that this error has started occuring.

alan-agius4 commented 2 months ago

I tried the above commands, and I am still not getting any error.

msalq commented 2 months ago

surprising, what node version are you using?

alan-agius4 commented 2 months ago

v18.20.3

msalq commented 2 months ago

I was able to replicate the bug on another machine, so im not really sure how its not happening on your end. We are running on M2 macbook.

alan-agius4 commented 2 months ago

@msalq, I also tried this on Mac and I am still unable to replicate used your reproduction.

alan-agius4 commented 2 months ago

I'm sorry, but we can't reproduce the problem following the instructions you provided. Remember that we have a large number of issues to resolve, and have only a limited amount of time to reproduce your issue. Short, explicit instructions make it much more likely we'll be able to reproduce the problem so we can fix it.

If the problem persists, please open a new issue following our submission guidelines.

A good way to make a minimal repro is to create a new app via ng new repro-app and add the minimum possible code to show the problem. Then you can push this repository to github and link it here.

angular-automatic-lock-bot[bot] commented 1 month ago

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.