What is the benefit of using multiple modules in angular? - javascript

I'm a familiar person with Angular Js, recently I've seen that in some projects multiple angular modules are created and assembled in main module.
The code looks like.
angular.module("main",['main.sub1','main.sub2','main.sub2'])
angular.module("main.sub1",[])
angular.module("main.sub2",[])
angular.module("main.sub3",[])
My questions are
When to approach such fashion of splitting modules ?
How it is useful ?
Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider for each separately)
If i inject a dependency in sub modules are they by default injected in main modules ?
I read few blogs but I'm not able to get a clear perception.
Can you please guide me through.

1.When to approach such fashion of splitting modules ?
Preferably, Always. But you don't really need to do it unless you have multiple apps that are using the exact same code, maybe the way you handle authentication in a few apps is identical, it would make sense to put the common code into a service and have that service as its own module. This offers code reuse, and we all know that code reuse is good.
2.How it is useful ?
Again, reusability is the key word here. You don't want to go around writing duplicate code. Code duplication is just plain wrong, and results in more expensive maintenance and more error prone code.
Another advantage is that modularising your applications explicitly outlines the dependencies of your application and separates the responsibilities of different parts of your app. Code reuse and separation of concerns are fundamental practices in writing maintainable code.
Another reason to separate your app into modules is performance. Right now I'm working on an app (web shop) which consists of 2 main sections: one section(app) for normal users/buyers/sellers, and another app for the admin. Now the users app needs some scripts/libraries the admin app doesn't, and vice versa. For example the admin app uses a kendo grid which requires a kendo.all.min.js script which when minified is 1.7MB! Now would it make sense to force all visitors to the site to download the heavy 1.7 MB script?
3.Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider
for each separately)
Yes. Ideally your applications will have different route/state configurations, so each app would have their own app.config(), this means you could define separate routes for each app using the shared modules. To my experience the main things you want to move into their own modules are services and directives, not applications routings.
4.If i inject a dependency in sub modules are they by default injected in main modules ?
Yes. If you inject a dependency X into a module A, and module A will be used by another module B then B will also inherit the dependency X.

A module is the kernel of functionality for Angular apps. Modules contain all of the code that we
write for our specific app and, thus, tend to grow huge in a monolithic way. Although this tendency
isn’t bad (modules are a great way to reduce global scope noise), we can divide our modules.
There are several differing opinions about when to create a module and when to nest functionality
in a global module. Both of the following methods are valid ways to break up our functionality by
modules:
1. When to approach such fashion of splitting modules ?
When you want to sepereate your app logic by functionality or by routes, is needed because as your code separated on modules, it easy to understand, to tests and etc. angular module system implementation of Module Pattern.
Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.
2.How it is useful ?
For starters, it's a lot cleaner for developers coming from an object-oriented background than the idea of true encapsulation, at least from a JavaScript perspective.
Your significant other is the new developer on the team who's been asked to fix a bug on one of the many screens in your app.
The developer sifts through the directory structure and sees all the controllers, models and services neatly organized. Unfortunately it tells him/her nothing about which objects are related or have dependencies on one another.
If at some point the developer wants to reuse some of the code, they need to collect files from a bunch of different folders and will invariably forget code from another folder somewhere else.
3.Does this affect routing[routeProvider/stateProvider] (since modules are defined differently can i place route provider or state provider for each separately)
Another method we can use to break up our app is to divide our modules by route. This breakdown
allows us to write isolated tests that focus on the functionality per route. Modularizing by route can
make more sense, depending upon the project; it allows us to divide our functionality efficiently
when we’re dealing with a lot of independent routes.
For instance:
angular.module('myApp.home', []);
angular.module('myApp.login', []);
angular.module('myApp.account', []);
angular.module('myApp', [
'myApp.home',
'myApp.login',
'myApp.account'
]);
This modularization makes sense specifically when we’re dealing with large numbers of routes
and/or when we don’t have too much cross-over between routes
4.If i inject a dependency in sub modules are they by default injected in main modules ?
shortly: yes. :)

Related

Modularizing the system independently - Micro Front-End or Monorepo (React)

Problem
Well, start with the problem at hand. Several systems support several functionalities, whether they are applications or pages, and most of them independently.
But for lack of planning, this system becomes a single and complicated project, being difficult to install or update.
The proposal would then be to modulate it, making parallel development, easy, and effective, since a change in an independent module would not impact the update of the entire system.
This concept is already well defined, but I am clearly looking for how far this is possible, and if it's worth it.
structure
The images above describe well what we intend to do in the system.
We intend to divide the system into independent modules, but that can share some things with each other, such as dependencies, interface design and global states.
Possible solutions - Pros and Cons
Here begins my question in question.
At the end of the construction of this project, we should have a system that can be developed separately for each module.
some solutions
Micro Front-End - React
Monorepo - React
Well, we know that there are several ways to configure a react project and launch it, and here begins another challenge.
Another important point is the generated build, it is interesting to keep the react pattern, in which several .js and .css files will be generated in a build folder, making it easy to launch it into production.
All modules would be using the same language (javascript) and the same framework (react).
Well, what would be the best alternative given this project scope? I read several articles demonstrating how to implement monorepo or micro front-end, but most were simple or didn't show the entire process, how to build etc.
A simple demo containing the above idea would also be interesting
I would go with monorepo approach specifically: https://turbo.build/
With this, I can have multiple packages in same repo as well as web apps at the same place.
I would structure them like this:
apps
- mainApp - App with module federation
- module1 - app hosted at /app1
- module2 - app hosted at /app2
- module3 - app hosted at /app3
packages
- app-container
- app-requests
- app-translations
- app-logs
- app-tracking
- app-state-management
With this approach, you can add more packages quickly and can have common utilities shared across multiple web apps. You can add multiple packages as your needs grow and quickly use them across the different web apps quickly specifically configuration-related things like sentry/datadog.
Later on, you can separate the apps and packages into multiple repositories if they get bigger and publish them as packages separately.
Additionally, you can have one main app that implements module federation and can use other apps independently deployed at their respective URLs. You can read more about module federation here: https://webpack.js.org/concepts/module-federation/

Migration to Angular: micro frontend w/ web components vs lazy loaded modules? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 months ago.
Improve this question
We have an large application spread across multiple teams, built with Java Server Pages. The goal is to migrate to Angular. A monolithic migration/launch was deemed not practical, so a gradual migration is preferred.
The idea is to use a Webpack 5 Module Federation app shell to load Angular micro frontend remotes into the existing JSP app. The question is whether to load the remotes as Angular apps or Web Components. The thought is that Web Components might allow them to embed a reusable microfrontend fragment into the JSPs in cases where they can't migrate an entire page at once, or they have components that will exist in both the unmigrated JSPs and the new Angular pages.
After the migration, they'll either keep the micro frontend architecture if it's justified, or abandon it and merge the remotes into one Angular app.
Another alternative might be lazy loaded modules rather than opening the pandora's box of micro frontend architecture. Just informally split the app up into lazy loaded modules per team. Downside here is possibly more teams stepping on each others toes in the repository, but that's no different than how they've been operating. Their concern about lazy loading modules is they don't think they'll be able to do something like this:
<!-- my ancient JSP site. LOL page load with every click -->
<JSP-header></JSP-header>
<myAngularComponent></myAngularComponent>
<script type="text/javascript" src="https://lawlcats.com/myAngularComponent.js"></script>
<JSP-footer></JSP-footer>
All in all, the proposed solution is incredibly complex. These teams are brand new to Angular and are already considering combining different frameworks within a micro frontend architecture, AND implementing web components. Sounds like a huge lift to me. I'm also unsure if they've considered how they'll manage the repository across teams.
Does anyone see room for improvement or flaws in this plan? I'd love suggestions for the micro frontend remotes being Angular vs Web Components, vs abandoning micro frontends altogether in favor of lazy loaded modules.
Well, it would be good if your team first fully grasped what are the implications of MFEs or WebComponents as tools.
Micro Frontends are self-contained, stateful, full-fledged, and fully black-box applications. Maybe it would help your team to think about them as iframes.
You stick a MFE app somewhere on your page, and that is it. It does its own thing. The host app just hosts all the MFE apps on all the different http ports, but it doesn't know anything about what's going on inside of them.
In the simplest classic example, there is no communication between the host and the apps, and the apps also never ever talk to each other. AFAIR, if you wanted them to communicate, it's theoretically possible to do that via http (since they do actually live on specific ports), or wild shenanigans like utilizing LocalStorage. But it's generally not easy.
WebComponents, on the other hand, are just raw components that do one specific thing. They are also black boxes, but usually super tiny and thin. You can think of them as something like input.
An input knows how it should be styled, it knows which raw browser Web APIs it should talk to, it knows that it should render text in response to the user typing on their keyboard, and how to expose a couple values and events to the external world. But ultimately, an input in itself is pretty dumb and can hardly be called an "application". It's just a small building block of the actual modern JS app.
inputs also don't talk to each other - why would they - but they expose clear, native html APIs for input and output, so the host app can very easily talk to them and make use of them. The host is still responsible for actually knowing how to do that though.
As for your use case, your options depend on your team's technical and business needs.
MFE Federation is a pretty strictly defined type of architecture. It might work in your use case, but you'll need to consider that trying to organize any kind of communication between these separate apps later on is asking for trouble.
On the other hand, if you really want to just have a bunch of modern JS components that you could stick anywhere in your existing JSP code, then WebComponents might be your best bet. IIRC, Angular components can be built and used as WebComponents like in your example, so it could be viable to write them in Angular (and then possibly migrate the entire app to an actual Angular SPA sometime later). The problem is that these components won't do anything by themselves, they still need the host page to actually use them.
It might also viable to write just one application with a bunch of lazy-loaded modules - which the standard straightforward case in modern Angular - and let it live under some specific routes. You would then just start rewriting pages in Angular one by one. Nobody likes that, but sometimes it's just what has to be done. As an upside, in that case at least you would have an actual modern Angular app as the host for all the JS components, instead of whatever JSP thing you currently have.
In theory you can mix-and-match approaches 2. and 3., with some pages only partially using the new shiny WebComponents, and some pages fully rewritten. It's probably what will have to eventually happen, but I'd try to initially stick to just 2 or just 3, to make the first steps of the migration simpler for your inexperienced devs.
Whether you choose Webpack MFE Federation, JS/Angular WebComponents, or a simple Angular SPA, I would strongly recommend looking into NX, which is a very powerful, framework-agnostic JS monorepo toolset. Among other features, it should help you solve the problem of managing the code between teams.
With NX, you can add arbitrary tags to all of your modules, and make the linter track and ban the dependencies between specific tags. As a simple example, your could say that modules tagged team-a cannot be used by team-b or team-c, so that Team A can safely do whatever they want in them without breaking anything that other teams actively use.

Best way to share components of lazy modules between lazy modules

I have a structure of over 20 modules that will have their components shared with each other.
Will I have to import all these components into the shared module? Is there a better structural organization?
Attention I know the concept of shared module. I would like to separate my components into modules and make them talk to each other.
Changed image for better understanding
You can have either one shared module or as many shared modules as you want depending on how much shared code you want to separate and how you want to split it.
Let's say you have two lazy modules that share one simple function in two lines. It's useless to create separated chunk for this function because it's better to load it in one single bundle once than having additional request.
On the other hand, if you thing that your initial startup bundle is too big and you know a big amount of code that can be moved to separated chunk, then just do it. Create another shared module that you will import only in two lazy modules which require it.
There is a great article on this top that will help you understand what it's going under the hood in Angular CLI code-splitting
Code-splitting in Angular or how to share components between lazy modules
Yes, it is a best practice to create a shared module for dependencies that are shared across all modules or you can create logically separated submodules and import them based on concrete needs.
https://github.com/fknop/angular-pipes?files=1 is a go to for me on making individual modules and combining many individual modules into a larger module. It handles pipes. But it is similar for components.
Customers and Users would be individual modules. And you would make a parent component that consumes both into CustomerUserComponent and facilitates communication between these subcomponents.
NGRX is a really good library built upon rx.js which helps handle communication in a queued fashion. Which becomes powerful when you combine async.

Benefits of creating new modules in my application

Could anyone explain me what is the pourpuse of create new modules in angularjs application, I have already read the documentation, but we are not quite sure about when is appropiate to create a new module or use our own application module when you create a new service, directive, etc..
I would like to add some thoughts after reading a bit more about the subject:
JAndy, you are right in the general concept, but to be more specific in when do you have to use angularjs modules I think I got a clear answer in this post
Basically we have 3 ways of structuring our angularjs projects:
angular-seed
Yeoman
Structure the project in Modules
Depending of how big is your project you can take one aproach or another.
Basically writing new modules in angularjs helps you to pack functionalities that are related, one of the advantages of this approach is if a new developer comes into your team he can get a general overview and find things easier than if you only have one module, another one is to reuse functionality accross other projects.
I'd like to answer this question in a more general style than being specific.
Why was the ISS not build as one gigantic station instead of multiple independent modules ? The reason behind modules is to separate responsibilities, decouple a construction, etc. In terms of programming it means to have logic, spread over multiple small modules. That way, you not only know exactly where to look if anything goes wrong or you need to extend some functionality, it'll also guarantee that your whole ISS( your application ) will not entirely fail if one of your modules fails. This of course, also requires certain aspects of
programming styles, most important in this context, to hold module interaction and communication loosely coupled (which I just assume).
So whenever you want to implement new stuff, which does not fit in any other existent code or module, you should create a new, independent module, which is specialized to fulfill a certain task.
Even if I'm not using AngularJS on regular bases, I'm sure the same idea of modularization will fit in there.

How to divide up a JavaScript codebase into modules?

The JavaScript in my web application has grown into one huge file. I want to break it up into modules so it's easier to manage.
I don't know if there are any established best practices for anatomizing the codebase of a web application, or if it just varies too much from project to project?
In particular:
should each module be responsible for an app-wide concept, such as "layout", or "clientside storage", etc?
or should modules be for concepts specific to the app being built (like "comments" or "calendar"), and each module be responsible for managing its own layout, its own clientside storage, etc?
or a mixture of both?
If you take Separation of Concerns and Single Responsibility into account then each module/component etc. should be responsible for doing what it does and nothing else. Break down your modules by re factoring into small, easy to manage chunks that do it's job and nothing else.
In terms of your JS application you could take a look at some client side MVC frameworks (such as knockout, sproutcore, spine etc. to name but a few) these frameworks help to logically separate out views and layouts to controllers and models. You might also be interested in using something like require.js to load your modules as and when they are needed.
There is a very good book by Alex McCaw which is worth a read.
MVC is just one pattern, but it is a very popular pattern and addresses some of the concerns you have.
Best of luck.
All things being equal, you are better to create your modules around concepts specific to the app. This is more object oriented, and tends to group together code that is more likely to change together. This in turn makes your code easier to understand, more tolerant of change, easier to develop and extend (the benefits of "modularity").

Categories