In this section, we are going to talk about dynamically importing modules and its related components. Say for instance, your CORE SPA is hosted on one server. And different teams are basically building different features as modules, which needs to be injected as part dependency injection. Idea is keeping Core part leaner and meaner. Then how could we achieve the same. In the last post, we have seen similar kind of post, where in we injected modules dynamically but, module was known at compile time as we have used webpack’s import which basically takes path to module as input parameter. In this case, module’s can be injected by reading some kind of metadata coming from somewhere. Hence, you can have get some JSON files with some metadata say what modules’ and related dependencies to load. Then, it will load accordingly
Let’s look at the code base:-
Now here, I am considering that Lazy module under lazy folder is sitting in some other repository or may be hosted at different endpoint, and from there, it should download the module based on the run-time inputs. Now, when I say runtime, inputs it comes like a metadata, which can have info like Module, Route Providers etc. Below, I have pasted the snippet of app.component.ts.
Here, on load basically, I am making use angular reflection to resolve the required modules and its dependencies say components, services on run time. Instead of webpack loader, here I am relying on SystemJsNgModuleLoader to load my required module. And, # syntax is the lazy load module syntax. This is nothing new in lazy load module. Here, in app.component.html, I have used #container as placeholder for injecting modules dynamically.
Now, app.module.ts file looks like
Here, I have used provideRoutes in providers section. Now, this can also be injected dynamically from metadata.
Once you login into this URL, this will present below result.
Now, if you see console, you can see factory logs for the same.
Download Code:- https://github.com/rahulsahay19/Dynamic-Import-Angular
Hope you would have liked this discussion. In Coming section, we will delve further around same. Till then stay tuned and Happy Coding.
686 total views, 1 views today