DEV Community

Manoj Sridhar
Manoj Sridhar

Posted on

ZoneJs Error Using Angular 18 with MVC Project

I have a project that uses MVC .cshtml pages and use Angular components loaded in razor pages either with script tag or using iFrame.

We had been using Angular 5 before and loaded the scripts as below

<script type="text/javascript" src="@Url.Content("~/dist/polyfills.bundle.js")"></script>

<script type="text/javascript" src="@Url.Content("~/dist/main.bundle.js")"></script>
Enter fullscreen mode Exit fullscreen mode

Now, we started converted it to Angular 18 and I tried to use the same pattern. Created new angular project using Angular cli.

ng new upgraded-angular

After doing ng build with default production configuration, I was using the following script to load the project.

<script type="text/javascript" src="@Url.Content("~/dist/upgraded-angular/browser/polyfills.js")"></script>

<script type="text/javascript" src="@Url.Content("~/dist/upgraded-angular/browser/main.js")"></script>
Enter fullscreen mode Exit fullscreen mode

This gave me the below error and the component was not loaded

zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten only when optimization is true.

Angular cli has correctly added zone.js to pollyfills as below in angular.json.

"polyfills": [
              "zone.js"
            ]
Enter fullscreen mode Exit fullscreen mode

I tried all the steps in online but nothing worked. I figured out that the same worked fine when I do npm run watch which is running the build in development configuration. Also found in production configuration, if I used Optimization:false, the error was not happening.

Later I found the culprit to be the type that we use to load the script. Due to the adoption of ES modules by angular recent versions, we had to use type="module" for the script files. I changed my script to below and then I am now able to load angular 18 components in mvc.

<script type="module" src="@Url.Content("~/dist/upgraded-angular/browser/polyfills.js")"></script>

<script type="module" src="@Url.Content("~/dist/upgraded-angular/browser/main.js")"></script>
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs