Creating a dynamic component loader with Angular CLI

Basically, I want to create a dynamic plugin system. I need to be able to deploy new plugins without having to reinstall the main plugin system.

Basically, if I was using SystemJS, I could just do something like

System.import(url).then(plugin => {
  this.createComponent(plugin.default);
});

      

url

is a dynamic thing - can read this from db or config etc.

The above might work - except I'm using the Angular CLI which uses Webpack. Using the CLI is a project-wide choice - so I'm stuck with Webpack and the CLI.

Since the Angular CLI does a lot of abstraction, I cannot change the webpack config (well, I can, but then I have to maintain it manually, which breaks simplicity again).

Webpack is not module loading, but the binder means it needs to know those modules beforehand and I can't just leave the new module somewhere and update the config so that it loads dynamically.

What are my options?

EDIT: Webpack has its own System.import, but it checks if the URL is static or dynamic. I could live with passing a static folder and dumping plugins into that folder - it just doesn't work anywhere other than the application itself.

+3


source to share


1 answer


Unfortunately, as far as I know, at the end of the day you need to add a dynamic component to the entryComponents

current module, otherwise Angular won't let you load it dynamically and it will complain.

So, anyway you need to statically put the component and put it inside entryComponents

, so don't use SystemJS or Something else, you can just create a dictionary and use it whenever you want:

import {MyComponentClass} from "somewhere";

const dictionary = {
    component1  = MyComponentClass
}

 this.createComponent(dictionary[urlOrName]);

      




Another possible solution would be to create a module for each component you are going to load dynamically, and then add that component to entryComponents

that module, that way you can import / load the module dynamically, but I'm not sure if you can add a dynamic module to the root the module is dynamic or not (the way the router does it with lazyLoading! ~~).

Angular was much simpler about dynamic components before they introduced AOT

, they honestly killed the simplicity by introducingAOT

+1


source







All Articles