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

Viewed 139789

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"
}
21 Answers

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
],

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/cli@8.3.8
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

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.

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.

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.

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".

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

install npm packages

npm i

then rebuild

ng serve

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

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.

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]
})

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.

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...

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.

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.

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

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';

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 {}

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

Try this

// run npm i

// then

npm audit fix

// and then rebuild

ng serve

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

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

Related