Omit select dormant modules when building (Angular5)

Currently, I am collaborating on a project that is being implemented across various customer instances. Within the project, we have several lazy loaded modules, with most of them being utilized by all customers. However, there are certain modules that are only required in specific locations, prompting me to consider excluding them from the build in all other areas.

Could this be achieved?

Answer №1

Have you considered implementing something similar to the following code snippet? (conditional loading of modules can be achieved using if statements, etc)

export class AppComponent implements AfterViewInit {

  @ViewChild('testOutlet', {read: ViewContainerRef}) testOutlet: ViewContainerRef;
  constructor(
    private loader: NgModuleFactoryLoader,
    private injector: Injector) {
    }

    ngAfterViewInit(): void {
    const path = 'src/app/lazy/lazy.module#LazyModule';
    this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
      const entryComponent = (<any>moduleFactory.moduleType).entry;
      const moduleRef = moduleFactory.create(this.injector);

      const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
      this.testOutlet.createComponent(compFactory);
  });
  }
}

Answer №2

Consider including the modules in the exclude section of your tsconfig.app.json configuration file

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
    "path/to/your/lazy.module.ts"
  ]
}

Make sure the path is specified relative to the baseUrl

It's important to consider your project setup (multiple app CLI project? One build per client?) to ensure each build has the appropriate configuration file

Answer №3

At this time, the current tooling does not support conditional loading of routes using the AOT compiler. Up to version 7, there is no built-in capability for this feature in the AOT compiler or CLI. While you can hide routes from users using router-guards, they must still be present during build due to NGC needing to analyze the router tree statically. In the future, there may be plans to address this limitation.

If you're looking to reduce build time, consider moving parts into libraries, although you'll still need a small module for lazy loading. It's important to note that libraries cannot be lazily loaded for the same reasons. There are ongoing discussions and issues related to this on GitHub - feel free to check out this for more information.

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

What could be causing the type errors I am encountering while trying to resolve this Promise within a generic function?

I am attempting to implement additional types within this WebSocket protocol: type Action = { action: "change-or-create-state"; response: string; } | { action: "get-state"; response: string | null; }; /** * map an action to its response ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

Obtaining data from a TypeScript decorator

export class UploadGreetingController { constructor( private greetingFacade: GreetingFacade, ) {} @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: (req: any, file, cb) => { if (process.env ...

I am unable to invoke this function: TypeError: this.fetchData is not a function

Whenever I try to execute this.fetchData();, I encounter the error "TypeError: this.fetchData is not a function". Initially, I suspected that the context of 'this' was lost so I attempted using bind and arrow functions without success. How can I ...

`Typescript does not adhere to the specified type when used inside a for loop with a local

This code snippet declares a variable venuelist of type Venue array and initializes it as an empty array. The type Venue has a property named neighborhood. There is a for loop that iterates through the venuelist array and checks if the neighborhoods matc ...

Error: The function webpackMerge.strategy does not exist

I've been in the process of updating an older Angular project to the latest version of Angular. However, I'm encountering a problem when trying to build, and I'm unsure why this is happening. Below is the error message that I've receiv ...

Angular 2 does not recognize the element 'child-selector' as valid

In my quest to establish communication from a child component to a parent component based on certain actions, I have incorporated the use of both EventEmitter and Output libraries. Let me walk you through what I have achieved thus far. Firstly, let's ...

Switch things up in the mat-tree angular

Is there a way to change the orientation of a mat-tree-node to "RTL" and adjust the padding to be on the right side? <mat-tree [dataSource]="dataSource" [treeControl]="treeControl"> <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggl ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

Using an external variable within an internal function in TypeScript

I am facing a situation where I have a variable outside of a function that needs to be updated, but I am unable to access it using "this" as it is not reachable at that point in the code. export class GamesDetailPage { details : any = {}; type : St ...

Navigating back to the starting point

I'm experiencing an issue while trying to navigate using the Router.navigate method. Despite following all instructions meticulously, whenever I attempt to route via API, it reloads the root page. Within my RootComponent implementation, I am utilizin ...

Unsuccessful file uploads with Angular using multer and Node/Express

Currently, I am facing an issue with single file upload using multer. While I can manually upload a file to the specified folder in the backend using tools like postman for testing the express route, the same functionality fails when trying to upload it th ...

Display or Conceal Multiple Divisions Using Angular 2

I am looking to implement a functionality using Li lists to toggle the visibility of multiple divs in Angular 2. Initially, all divs on the page will be visible. When viewing on a smaller screen, I want to hide some divs and show a specific div when a cor ...

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

Are union types strictly enforced?

Is it expected for this to not work as intended? class Animal { } class Person { } type MyUnion = Number | Person; var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail? var x: MyUnion = "jjj"; // Should this actually ...

How can I utilize Luxon to calculate the total number of days that are equal to or greater than 30?

Looking at my current array structure const arr = [ { id: '1', name: 'thing1', createdAt: '2022-09-21T16:26:02Z', }, { id: '2', name: 'thing1', createdAt: '2022-11-21T16:20:20Z', } ...

Include a tab button within a vertical tab list using Angular Material

I have utilized Angular Material to create a vertical tab, and I would like to incorporate an Add Tab button within the tab listing itself. Currently, when I add the button, it appears at the bottom of the layout instead. For reference, you can access the ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...

Dynamically Disabling Form Control in Angular 2

There is a basic form with two form controls that initially have required validation. In addition to the form controls, there is a button in the template. When this button is clicked, it triggers a change in the behavior of the form group. Both form contr ...

Detecting when Angular2 input values change

Here is the updated code snippet: I am attempting to modify an input field and then submit the form. However, when I retrieve the form data using server-side code, the input has not been updated. <form id="cardsForm" method="post"> <inpu ...