The use of function calls is not allowed in decorators during ng build --prod (AOT) compilation

Type of Concern: Bug / Question

Issue Details

I'm currently utilizing the ng-packagr library to compile my code into JavaScript. The compilation process runs smoothly without any errors, however, when attempting to consume the library with 'ng build --prod' (AOT enabled), I encounter the following error:


ERROR in Error during template compile of 'AppModule' Function calls are not supported in decorators but 'BsDropdownModule' was called.

If I remove the '.forRoot' method, a different error occurs:


ERROR in : Unexpected value 'BsDropdownModule in /home/sf/Desktop/Developerka/kompilacja/final/sample-repo/node_modules/angular-library-name/free/dropdown/dropdown.module.d.ts' imported by the module 'AppModule in /home/sf/Desktop/Developerka/kompilacja/final/sample-repo/src/app/app.module.ts'. Please add a @NgModule annotation

It's important to note that using ng --prod --aot=false does not result in any errors.

Steps to Recreate:

To replicate the issue, please download the repository from: https://github.com/Bloodcast69/aot-error, then execute the commands npm install followed by ng build --prod.

Expected Outcome

The desired outcome is to successfully build with AOT without encountering any errors (this compatibility is required for Angular Universal).

Version Information


ng-packagr: 2.4.1
@angular/*: 5.2.9
typescript: 2.5.3
rxjs: 5.5.6
node: 8.1.0
npm/yarn: npm: 5.6.0

Files Involved:

app.module.ts:

import { BsDropdownModule } from 'angular-library-name';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';



import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BsDropdownModule.forRoot(),
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

dropdown.module.d.ts:

import { ModuleWithProviders } from '@angular/core';
export declare class BsDropdownModule {
    static forRoot(config?: any): ModuleWithProviders;
}

dropdown.module.ts (before compiling to JS):

import { ModuleWithProviders, NgModule } from '@angular/core';
import { ComponentLoaderFactory } from '../utils/component-loader/index';

import { PositioningService } from '../utils/positioning/index';
import { BsDropdownContainerComponent } from './dropdown-container.component';
import { BsDropdownMenuDirective } from './dropdown-menu.directive';
import { BsDropdownToggleDirective } from './dropdown-toggle.directive';
import { BsDropdownConfig } from './dropdown.config';

import { BsDropdownDirective } from './dropdown.directive';
import { BsDropdownState } from './dropdown.state';

@NgModule({
  declarations: [
  BsDropdownMenuDirective,
  BsDropdownToggleDirective,
  BsDropdownContainerComponent,
  BsDropdownDirective
  ],
  exports: [
  BsDropdownMenuDirective,
  BsDropdownToggleDirective,
  BsDropdownDirective
  ],
  entryComponents: [BsDropdownContainerComponent]
})
export class BsDropdownModule {
  public static forRoot(config?: any): ModuleWithProviders {
    return {
      ngModule: BsDropdownModule, providers: [
      ComponentLoaderFactory,
      PositioningService,
      BsDropdownState,
      {provide: BsDropdownConfig, useValue: config ? config : {autoClose: true}}
      ]
    };
  };
}

NOTE I have extensively searched online for solutions to this issue but have been unsuccessful. I have reviewed the following resources:

FeatureModule fails during an AOT build when static forRoot has arguments

https://github.com/angular/angular/issues/14707

If additional information is required to assist in resolving this problem, kindly let me know and I will provide it promptly.

Thank you, Bloodcast69

Answer №1

Encountering an issue with AOT: the forRoot function must be executed during compile-time. If using a more recent version of Angular, this should resolve itself, but if not, adjusting the tsconfig.app.json file may help. Take a look at this related inquiry: Angular 6 Prod Function calls are not supported in decorators but '..Module' was called

Answer №2

Ensure that your forRoot method returns a ModuleWithProviders and is properly annotated with @NgModule

  import { ModuleWithProviders, NgModule } from '@angular/core';

    @NgModule({
        declarations: [],
        imports: [],
        providers: [],

      })
    export class BsDropdownModule {
       // constructor(parentModule: BsDropdownModule);
        //  static forRoot(config?: any): ModuleWithProviders;
        static forRoot(config?: any): ModuleWithProviders {

            return {
                ngModule: BsDropdownModule,
                providers: [
                ]
            }
        }
    }

Remember to import the dropdown.module in your app.module, not the declaration file dropdown.module.d.ts

import { BsDropdownModule } from './dropdown.module';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BsDropdownModule.forRoot(),
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I have tested this with an AOT build and encountered no errors.

Answer №3

I too encountered a similar problem, after some investigation I found that the issue lies with ng-packagr. I isolated my module from the library and tried it in a standalone application without any AOT errors. The error only occurs when I bundle my module into a library.

My setup includes Angular 6.1.8 and ng-packagr version 4.2.0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to log out firebase user

Currently, I am attempting to sign out the user who is already signed in within my Angular app. Here is my client service code: export class AuthClientService { public register(email: string, password: string): Observable<Object> { retu ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...

Is `TypeDefinition for React v15.0` compatible with React v0.14.7?

Within the project I am currently working on, we have incorporated React v0.14.7. After using npm, I executed the following command: npm install --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbea9adafb88cfce2fdf8e2fb ...

No results found in MongoDB query when using find method

Having an issue with an API call to my express server to retrieve employees working in the same location based on the location ID. Strangely, the API call returns an empty array while it functions correctly in the command-line interface. Definition of Emp ...

Unable to execute two queries in the MariaDB SQL server due to a syntax error when utilizing Angular in conjunction with Sequelize

I encountered an issue while attempting to delete records from two separate tables in my database using a SQL command. The goal was to merge two queries for deletion. defaultAdapter.query('DELETE FROM reasons WHERE name = :name') defaultAdapter. ...

What are the steps to replicate a node that includes an Angular selector using TypeScript?

My Angular app has a peculiar issue. In one component, my HTML includes a selector of another component within a div like this: <div id="header"> <selector> Text Content </selector> </div> When I try to clone this d ...

The incorrect argument is being used to infer the generic type

I have implemented the NoInfer feature from the library called ts-toolbelt. However, it seems that the example provided below does not reflect its intended effect. In this scenario, the generic type is deduced from the util function as soon as it is intr ...

What is the importance of adding the ".js" extension when importing a custom module in Typescript?

This is a basic test involving async/await, where I have created a module with a simple class to handle delays mymodule.ts: export class foo { public async delay(t: number) { console.log("returning promise"); ...

"View your daily schedule in half hour intervals with the Angular calendar feature

I am currently utilizing the Angular calendar, which can be viewed at . My objective is to divide the hour into half-hour segments. Following the information provided here: https://github.com/mattlewis92/angular-calendar/issues/287 I have implemented the ...

Unable to Trigger Ion-Slide.slideNext() in Ionic 6 Angular using custom button event

I created a home component that includes a slider-item component containing ion-slides. Within the home component, I added an ion-header with Previous and Next Buttons. Here is the code from home.page.ts: import { Component, ViewChild } from '@angula ...

Is it possible to ensure that all values from a specific type are represented in an enum collection?

I have a Prisma enum that I've defined (not in TypeScript), and I'm curious if it's possible to synchronize a TypeScript String enum with the generated Type from the Prisma Client. Here are the key details: export const GroupInvitationSta ...

The response type for HTTP Get in Typescript is specified as "text"

I'm currently working on a Typescript HTTP Get request and need to customize the response type as text. Here's my code snippet: getMessageContent(messageContentId?: string): Observable<string> { const url = this.commonService.getApi ...

Tips for effectively managing RxJS Observables when synchronization of data is crucial

Hopefully the topic is clear enough. I am relatively new to working with RxJS and Redux. Currently, I am developing an Angular 2+ application using Observables and NgRX store. Within the store, there are multiple sections. My goal is to extract propertie ...

Working with bulk operations on a RESTful API using Angular

When attempting bulk operations on JSON data from Angular using HttpClient, I encountered an issue where it only updates the last checked record instead of updating the entire JSON. Seeking assistance to rectify this problem. I believe a bulk operation ne ...

When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string. Here is what I aim to achieve with my output: "This is an example!" ==> "sihT ...

Issue with the alignment of cards in the group of cards

Struggling to align the bottom sections of these elements. Despite consulting Bootstrap references, I can't figure out what's causing this misalignment. I thought using the card-group class would align the bottoms of its children, but it doesn&a ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

Avoid risky assigning value of type `any`

Currently, I am incorporating TypeScript into my client-side application. However, upon running the application, I encounter two specific errors: @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an `any` value. @typescript-eslint/no-unsafe-me ...

What is the best way to transform a string into an array?

After receiving an object from the http response, it looks something like this: {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] } The key in the object is represented as an array. Is there a method in ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...