77

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"
}
5
  • What commands are you using to build for the server? Commented Mar 15, 2020 at 8:03
  • @Vinaayakh ng build --prod Commented Mar 15, 2020 at 8:39
  • maybe try adding the --aot flag as well? You could also check if all of your packages are updated Commented Mar 15, 2020 at 8:46
  • @Vinaayakh how can i do this ? Commented Mar 15, 2020 at 9:02
  • Just close the application and restart from the beginning, worked for me. Commented Feb 8, 2023 at 10:08

29 Answers 29

138

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
],
Sign up to request clarification or add additional context in comments.

1 Comment

@D. Squire i haven't add Material but still i am getting error.
34

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

2 Comments

without Ivy it works but there's serious benefit having Ivy. According to what I've read, js size reduce dramatically with it.
I add the last solution and worked correctly "angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true, "enableIvy": false }
26

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.

Comments

17

Sometimes it helps to just clear the Angular cache.

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

3 Comments

I've run into this error after switching between branches that have different packages installed. Deleting the .angular folder usually works in that case. Sometimes npm install is also required.
This solved the issue for me after I refactored a component into a new module.
I deleted .angular and the dist folder, then rebuilt. Was fine after.
15

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.

1 Comment

this "answer" should be a comment
8

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.

1 Comment

This was the solution for me too. I got the error after upgrading from Angular v14 to v15. In my app.module.ts was an unused import of the HomeComponent. The HomeComponent was not in the declarations or imports array, but still caused this error.
6

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

install npm packages

npm i

then rebuild

ng serve

Comments

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.

Comments

2

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

1 Comment

I unfortunately only found this answer after wasting time and finding fix myself. Basically "compilationMode": "partial" needs to be in tsconfig.lib.json​ and NOT in tsconfig.json. This way it will only be applied to library, and not project.
2

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.

2 Comments

This actually solved my problem, but I don't understand how is this different from importing from @my/foo? For anyone having same issues with cypress here is some additional info: github.com/nrwl/nx/issues/7805#issuecomment-974320990
Importing @my/foo likely imports other things as well that depend on Angular, which is not available in the Cypress context and therefore fails to build.
2

Try this

// run npm i

// then

npm audit fix

// and then rebuild

ng serve

1 Comment

Running npm i might be usefull for some people, but npm audit fix has nothing to do with this kind of problem!
1

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

Comments

1

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

Comments

1

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

1 Comment

This was downvoted, but I found this happening to me as well. Sometimes (especially when I've been changing modules, routes, etc) I have to re-serve the app to get past this. So it seems like you and I have the same issue - but not related to the context of this question
1

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.

Comments

1

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

example of the code

Comments

0

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

Comments

0

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.

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

0

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.

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

0

i just ran npm install and everything went back to normal

Comments

0

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

Comments

-1

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.