kianoush dortaj
kianoush dortaj

Reputation: 797

Uncaught (in promise): Error: Angular JIT compilation failed: '@angular/compiler' not loaded! in angular 9

I create a webaite with angular 9 but i have a problem with angular .

In some route I have the error:

ERROR Error: Uncaught (in promise): Error: Angular JIT compilation failed: '@angular/compiler' not loaded!
  - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.
  - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?
  - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.
Error: Angular JIT compilation failed: '@angular/compiler' not loaded!
  - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.
  - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?
  - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.

But in some routes I do not have this error. Another weird thing is that in local it works fine but in server it did not work. What's the problem and how can I solve it?

In my server I place the put the files in the app folder, while in the local machine I don't have this folder.

Here is angular.json:

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "newProjectRoot": "projects",
    "projects": {
        "avastar": {
            "root": "",
            "sourceRoot": "src",
            "projectType": "application",
            "prefix": "kt",
            "schematics": {
                "@schematics/angular:component": {
                    "style": "scss"
                }
            },
            "architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                        "outputPath": "dist/avastar",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.app.json",
                        "assets": [
                            "src/favicon.png",
                            "src/assets"
                        ],
                        "styles": [
                            "src/styles.scss"
                        ],
                        "scripts": [
                            "src/assets/vendors/global/vendors.bundle.js",
                            "src/assets/js/demo1/scripts.bundle.js"
                        ],
                        "stylePreprocessorOptions": {
                            "includePaths": [
                                "src",
                                "src/stylings/",
                                "src/stylings/base/",
                                "src/stylings/kt-customs/"
                            ]
                        },
                        "es5BrowserSupport": true
                    },
                    "configurations": {
                        "production": {
                            "fileReplacements": [{
                                "replace": "src/environments/environment.ts",
                                "with": "src/environments/environment.prod.ts"
                            }],
                            "optimization": true,
                            "outputHashing": "all",
                            "sourceMap": false,
                            "extractCss": true,
                            "namedChunks": false,
                            "aot": true,
                            "extractLicenses": true,
                            "vendorChunk": false,
                            "buildOptimizer": true,
                            "budgets": [{
                                "type": "initial",
                                "maximumWarning": "5mb",
                                "maximumError": "10mb"
                            }]
                        }
                    }
                },
                "serve": {
                    "builder": "@angular-devkit/build-angular:dev-server",
                    "options": {
                        "browserTarget": "avastar:build"
                    },
                    "configurations": {
                        "production": {
                            "browserTarget": "avastar:build:production"
                        }
                    }
                },
                "extract-i18n": {
                    "builder": "@angular-devkit/build-angular:extract-i18n",
                    "options": {
                        "browserTarget": "avastar:build"
                    }
                },
                "test": {
                    "builder": "@angular-devkit/build-angular:karma",
                    "options": {
                        "main": "src/test.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.spec.json",
                        "karmaConfig": "src/karma.conf.js",
                        "styles": [
                            "src/styles.scss"
                        ],
                        "scripts": [],
                        "assets": [
                            "src/assets"
                        ]
                    }
                },
                "lint": {
                    "builder": "@angular-devkit/build-angular:tslint",
                    "options": {
                        "tsConfig": [
                            "src/tsconfig.app.json",
                            "src/tsconfig.spec.json"
                        ],
                        "exclude": [
                            "**/node_modules/**"
                        ]
                    }
                }
            }
        },
        "avastar-e2e": {
            "root": "e2e/",
            "projectType": "application",
            "prefix": "",
            "architect": {
                "e2e": {
                    "builder": "@angular-devkit/build-angular:protractor",
                    "options": {
                        "protractorConfig": "e2e/protractor.conf.js",
                        "devServerTarget": "avastar:serve"
                    },
                    "configurations": {
                        "production": {
                            "devServerTarget": "avastar:serve:production"
                        }
                    }
                },
                "lint": {
                    "builder": "@angular-devkit/build-angular:tslint",
                    "options": {
                        "tsConfig": "e2e/tsconfig.e2e.json",
                        "exclude": [
                            "**/node_modules/**"
                        ]
                    }
                }
            }
        }
    },
    "defaultProject": "avastar"
}

Upvotes: 74

Views: 223431

Answers (29)

Asamoah
Asamoah

Reputation: 489

I had this happen to me when I had @NgModule declared twice in one of my routing modules. Removing the redundant one resolved the issue.

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})

@NgModule({ 
  declarations: [],
  imports: [CommonModule],
})

Upvotes: 0

Buk1m
Buk1m

Reputation: 99

In my case it was due to import order in main.ts platformBrowserDynamic import must be before the AppModule

See my answer here: https://stackoverflow.com/a/78489351/12024079

Upvotes: 0

Felani
Felani

Reputation: 1

i just ran npm install and everything went back to normal

Upvotes: 0

Rens
Rens

Reputation: 745

Sometimes it helps to just clear the Angular cache.

  • Delete the .angular folder in your project
  • Restart your application

Upvotes: 16

fahadash
fahadash

Reputation: 3281

Posting this here so someone else might find it useful in the future.

I had a very similar issue, JIT Compiler exception in angular bootstrapping but different type of exception. After lengthy troubleshooting steps I found that angular 15 wasn't compatible with ASP.NET Framework 4.8 Web Forms application.

My angular app was just a widget that fits into an ASP.NET Web Forms page.

In my case a native prototype method of an intrinsic js type was changed by a .NET Framework assembly that was spitting out some javascript polyfills and was doing parameter checks.

You might find my troubleshooting steps and the hack useful in this answer here.

Upvotes: 0

רותי גליק
רותי גליק

Reputation: 11

I had the same issue also. I simply replaced BrowserAnimationsModule to be first of app.module.ts

example of the code

Upvotes: 1

Tampambro
Tampambro

Reputation: 1

Ubuntu 22.04

Nothing above didn't help me. I solved problem in this way:

  1. Delete node_modules and angular cache;
  2. In folder, where node_modules must installing, change umask like this umask 000;
  3. Install packages and run.

In sum up.

Most likely, when packages installing or angular compiling app - ubuntu do permission denied somewhere.

Upvotes: 0

gline9
gline9

Reputation: 73

We ran into this problem due to the angular auto upgrade scripts adding an additional @Injectable() annotation to one of our services. Double check that you have removed the duplicate annotation from any code it produced that may look similar to the following.

import { Injectable } from "../../../../node_modules/@angular/core";
import { Injectable as Injectable_1 } from "@angular/core";

@Injectable()
@Injectable_1()
export class Service {
}

Further, what helped us triage the issue was to comment out module imports for AppModule doing a binary search on what imports cause the issue and which don't until we found the problematic module. Then further binary searching by commenting out the individual services, components and directives of that module until we found the problematic one.

Upvotes: 1

Andre TOKAM
Andre TOKAM

Reputation: 371

Try this

// run npm i

// then

npm audit fix

// and then rebuild

ng serve

Upvotes: 2

Ramón Espinosa
Ramón Espinosa

Reputation: 339

I solved this error simply by running a npm install inside the terminal

Upvotes: 0

Bayu
Bayu

Reputation: 2644

I got the same message, I believe I have a different case with people already answered here ( maybe different from the one who initially asked the question too ).

My case was:

  1. Update some libraries ( as I remember, it was ngx-spinner and ngx-datatables )
  2. Using angular 13.

I believe that makes my case different than the others here is because I am using Angular 13 and updating things which initially was angular 8. Of course, I gradually upgrade the project from 8 to 13.

THE SOLUTION for me was:

  1. Stop the ng serve script
  2. Delete directory node_modules and .angular
  3. Run npm install or yarn install
  4. Execute the ng serve again

Compared to the existing answer here, which is suggesting to delete node_modules only, my solution was to delete .angular directory too. It's supposed to be the cache for Angular project I guess. I assume it because deleting node_modules only doesn't work for me.

Upvotes: 26

Perry
Perry

Reputation: 312

I solved it by exporting the RouterModule from the feature components

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { QuestionsComponent } from './questions/questions.component';

const routes: Routes = [{ path: 'questions', component: QuestionsComponent }];

@NgModule({
  imports: [RouterModule, RouterModule.forChild(routes)],
  exports: [RouterModule], // this export might be missing
})
export class QuestionsRoutingModule {}

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657308

I import an @my/foo from an Nx module into a Cypress test which also exports Angular related code.
Importing individual files `lib/foo/src/lib/foo' instead fixed it.

Upvotes: 1

hazan kazim
hazan kazim

Reputation: 958

This issue can be generated due to incompatibility of some dependency versions.

install npm packages

npm i

then rebuild

ng serve

Upvotes: 6

user721730
user721730

Reputation: 488

My problem was in app.modules.ts:

import { HttpClientModule, HttpClient } from '@angular/common/http';

I removed HttpClient and it works: import { HttpClientModule } from '@angular/common/http';

Upvotes: 0

GMON
GMON

Reputation: 56

I had the same issue and what fixed it for me was an oversight with @Component.

@Component has to be right above the class its referring to.

screenshot

Upvotes: -1

leonar2zb
leonar2zb

Reputation: 1

I had a similar situation. I coded an Angular 8 app then restarted it after upgrading my Angular cli to v12. I've solved running npm update but then got a new error with flexlayout. I ran npm i -s @angular/flex-layout @angular/cdk and solved my problems

Upvotes: 0

Petar
Petar

Reputation: 21

I had similar error using angular 12:

The injectable needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.

This was the post I was stumbling across, so thought to put an answer here if someone else experience this issue as well.

In my case I had lib compiled with ivy with option "partialy":

"compilationMode": "partial"

Angular app was also compiled in this mode and that was causing the issue. App that uses this lib should be compiled with default option "full".

Upvotes: 2

Enrico
Enrico

Reputation: 3454

As suggested already, make sure you always import the module and not the component!

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SharedModule } from './shared/components/shared.module';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, SharedModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

I imported a component I defined in my SharedModule here by mistake.

This article helped me find the problem.

Upvotes: 8

samivic
samivic

Reputation: 1310

i just stop the application and i run it with 'ng serve' and strangely it runs!

Upvotes: 1

Pedro A
Pedro A

Reputation: 4323

In my case, I had {{ typeof someValue }} inside a component template, I wrote it quickly to debug something else but it turns out typeof does not work in there, and gives this weird error instead.

Upvotes: 0

Edison
Edison

Reputation: 510

The line "buildOptimizer": true will exclude @angular/compiler from the built result. The line "optimization": true will somehow remove related code of dynamic created component based on JIT compiler, I'm not very clear of this. But the workaround below will fix both of them.

angular.json

# other lines are ignored
{
  "projects": {
    "app-web": {
      "architect": {
        "build": {
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js",
              "mergeStrategies": {
                "module.rules": "append",
                "resolve": "append"
              },
              "replaceDuplicatePlugins": true
            }
          }
        }
      }
    }
  }
}

webpack.config.js

module.exports = (options) => {
  if (options.optimization && options.optimization.minimizer && Array.isArray(options.optimization.minimizer)) {
    (options.optimization.minimizer).forEach((plugin) => {
      if ((plugin.options || {}).terserOptions) {
        const terserOptions = (plugin.options || {}).terserOptions;
        terserOptions.compress = {
          side_effects: false,
        };
      }
    });
  }
  return {
    // other lines are ignored
    ...options
 }
};

However, the size of built result will be increased.

Here are some references you can take a look.

Upvotes: 0

Anant Shekhar
Anant Shekhar

Reputation: 117

This error generally comes when we don't import any particular module or import any module improperly. I was also getting same error once and importing BrowserAnimationsModule in a module.ts file worked for me at that time.

First import it like this:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

Then add the module inside imports array of module.ts file:

@NgModule({
  declarations: [NavBarComponent],
  imports: [
    CommonModule,
    MatToolbarModule,
    MatIconModule,
    BrowserAnimationsModule, //<----------
  ],
  exports:[NavBarComponent]
})

Upvotes: 1

J King
J King

Reputation: 4434

I hate these kind of answers but it worked for me, ha.

Using Angular 11 in my project

I deleted the node_modules folder and reinstalled the modules then rebuilt my project in dev and the compiler error went away.

Upvotes: 15

Sarthak Maheshwari
Sarthak Maheshwari

Reputation: 537

For me, this issue was due to the wrong declaration in the declarations array of the module. I did declare something which was not part of that module.

declarations: [DropDownModule],
imports: [DropDownModule, CommonModule]

This DropDownModule is not a part of the module.

Upvotes: 2

Basher Sarkar
Basher Sarkar

Reputation: 116

In my case I'm facing same problem after upgrade Angular 9 to 10. In Angular 10 simply remove "postinstall": "ngcc" from package.json and "angularCompilerOptions": { "enableIvy": true } from tsconfig.app.json.

May be this can help you.

Note:

In Angular cli 9 they Introduce new compiler Ivy and for set up Ivy compiler in project you can add bellow line in respective files

  1. "postinstall": "ngcc" in package.json
  2. "angularCompilerOptions": { "enableIvy": true } in tsconfig.app.json
  3. "aot": true in angular.json

But With Angular 10 they set default compiler to Ivy. So that need to remove option 1 and 2

Upvotes: 1

D. Squire
D. Squire

Reputation: 1551

If you are like me and wound up here from google. My error came when I included an Angular Material Component, rather than it's module in app.module.ts

special note: whenever you add a new material module to app.module.ts you must stop (and restart) ng serve or you will get this error.

change this

imports: [
   BrowserModule,
   HttpClientModule,
   AppRoutingModule,
   BrowserAnimationsModule,
   MatDialog, // <====== this is the error
],

to this

imports: [
   BrowserModule,
   HttpClientModule,
   AppRoutingModule,
   BrowserAnimationsModule,
   MatDialogModule, // <====== this is the solution
],

Upvotes: 136

Joshua Michael Calafell
Joshua Michael Calafell

Reputation: 3107

This error can also be thrown if there are any files in the files array in tsconfig.app.json that Aren't modules.

Having a non-module in the tsconfig causes the JIT and AOT compilers to fail on serve or build.

Before:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts",
    "./src/app/<non-module>.ts", // <-- The culprit
  ],
  "include": ["src/**/*.d.ts"]
}

After

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"]
  },
  "files": ["src/main.ts", "src/polyfills.ts"],
  "include": ["src/**/*.d.ts"]
}

Simply remove the culprit...

Upvotes: 0

Lalana Chamika
Lalana Chamika

Reputation: 615

This is actually an issue with the angular 9 versions. There are mainly 3 different ways to fix this issue as the angular-cli haven't fixed this yet. (You can view the issue in https://github.com/angular/angular-cli/issues/16873),

Solution 1

Update all the dependencies in your node-modules (This issue can be generated due to incompatibility of some dependency versions) run npm update in the project terminal to update all dependencies.

Solution 2

If the above solution didn't work add aot= true in angular.json and add "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points" in package.json and then delete node_modules and package lock file and install again.(https://github.com/angular/angular/issues/35788#issuecomment-627514285)

Solution 3

If non of the above worked, it would be a better option to downgrade the angular cli version globally. Because this issue have not been bugging in angular cli version 8 and 7.

ng --version
npm uninstall -g @angular/cli
npm cache clean --force

npm install -g @angular/[email protected]
ng --version

............................................................................................................................................................

Update (30.07.2020)

Some folks have over comed this issue by disabling ivy engine on tsconfig.json file:

"angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true, "enableIvy": false }

Reffer : https://github.com/angular/angular/issues/35788#issuecomment-650550297

Upvotes: 32

Related Questions