1

My company added an Angular app to the existing ASP.NET MVC project last year. The Angular index host webpage is a .cshtml file that contain razor code, eg @RenderSection("SharedCss", false) .

It works fine until we upgrade to Angular 12 last week. When build the Angular app with optimization option ( ng build --optimization ), the output index.cshtml file is modified erroneously.

Original index.cshtml file

<!DOCTYPE html><html lang="en">
  <head>
    <base href="/">

    <!-- razor code start-->
      @RenderSection("SharedCss", false)
    <!-- razor code end-->

  </head>
  <body>
    <app-root>Loading...</app-root>
  </body>
</html>

Expected result

<!DOCTYPE html><html lang="en">
  <head>
    <base href="/">

    <!-- razor code start-->
      @RenderSection("SharedCss", false)
    <!-- razor code end-->

    <style>:root{--blue:#007bff;.........</style>
    <link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">
    <noscript><link rel="stylesheet" href="styles.css"></noscript>

  </head>
  <body>
    <app-root>Loading...</app-root>
    <script src="runtime-es2015.js" ............ </script>
</body>
</html>

Erroneous result

<!DOCTYPE html><html lang="en">
  <head>
    <base href="/">

    <!-- razor code start-->
      </head><body>@RenderSection("SharedCss", false)
    <!-- razor code end-->

    <style>:root{--blue:#007bff;.........</style>
    <link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">
    <noscript><link rel="stylesheet" href="styles.css"></noscript>

    <app-root>Loading...</app-root>
    <script src="runtime-es2015.js" ............ </script>
</body>
</html>

The </head><body> html is erroneously moved to before the razor code (see line between <!-- razor code start--> and <!-- razor code end-->). It seems during the build optimization process, when Angular cannot parse the unexpected html syntax (eg. razor code) in the head tag, then it would append the </head> tag to end the html head element.


Note:

  1. To eliminate the upgrade factor, I create new empty Angular app, and the issue still exist.
  2. this occurs after Angular 12+

I have not be able to find anyone mention this behavior/issue. I would still want to turn the optimization flag on when build for production environment. Please help!

Andy Chang
  • 11
  • 2

1 Answers1

0

My colleague found the workaround solution base on this stack overflow post

We apply the same fix by disabling the inlineCritical option.

here is an example workspace configuration

  "optimization": {
     "scripts": true,
     "styles": {
        "minify": true,
        "inlineCritical": false
     },
     "fonts": true
  }
Andy Chang
  • 11
  • 2