Angular Microfrontends with NX and Module Federation

Sebastian Persson
23 Jul 202325:43

Summary

TLDREste video explora el uso de micro front-ends y la estructura de monorepos con NX, enfocándose en la arquitectura de micro front-ends con Angular. Se discuten las ventajas y desventajas de utilizar la arquitectura de micro front-ends y se muestra cómo se puede implementar usando la herramienta NX. Además, se explica cómo trabajar con bibliotecas compartidas y se destaca la facilidad de integración y actualización de componentes en diferentes aplicaciones, mejorando el flujo de trabajo en proyectos de gran envergadura.

Takeaways

  • 🌟 Micro front end es una arquitectura que permite diferentes aplicaciones o micro aplicaciones ser servidas al mismo tiempo en diferentes frameworks o librerías.
  • 🛠️ Module Federation es una alternativa para lograr micro front ends, permitiendo la despliegue individual de cada aplicación.
  • 📈 Las ventajas de utilizar micro front end incluyen la capacidad de equipos con experiencias diferentes trabajar en diferentes tecnologías y la posibilidad de tener equipos autónomos.
  • 🔧 La estructura de un monorepo con NX permite tener múltiples proyectos de front end, así como backend, en un solo repositorio, facilitando la colaboración y mantenimiento.
  • 🎉 Utilizar NX para la estructura monorepo trae consigo muchos beneficios, como la facilidad de generar nuevas aplicaciones y componentes, y la capacidad de manejar diferentes configuraciones.
  • 🔄 La generación de aplicaciones con NX incluye la opción de incluir características como TypeScript, SCSS, y la capacidad de generar aplicaciones backend con Node y Nest.
  • 🔗 La integración de aplicaciones remotas y host se logra a través de la configuración de Module Federation, permitiendo la conexión y comunicación entre ellas.
  • 🛠️ La generación de componentes compartidos, como un botón en este caso, permite su uso en diferentes aplicaciones y mejora la reutilización de código.
  • 📋 La estructura de archivos y directorios en NX sigue un modelo mental que separa lógica de negocio de componentes, facilitando la creación de librerías compartidas.
  • 🔄 Las actualizaciones en componentes compartidos son fáciles de implementar y se ven reflejadas en todas las aplicaciones que los utilizan.
  • 🚀 NX ofrece una integración sencilla con CI/CD, permitiendo la ejecución de pruebas y actualizaciones en las aplicaciones afectadas por cambios en componentes compartidos.

Q & A

  • ¿Qué es un micro frontend y cómo se relaciona con diferentes frameworks o librerías?

    -Un micro frontend es un enfoque para desarrollar aplicaciones web monolíticas en la que se utilizan diferentes variantes de frameworks o librerías. Permite a diferentes equipos trabajar en diferentes partes de la aplicación sin interferir entre sí, lo que es útil en entornos de gran escala y colaboración multidisciplinaria.

  • ¿Cuál es la ventaja de utilizar Module Federation en lugar de otros enfoques para micro frontends?

    -Module Federation permite la descomposición de aplicaciones en micro aplicaciones que se pueden servir de manera independiente y combinar en una sola aplicación. Ofrece flexibilidad y permite a los equipos trabajar con diferentes tecnologías y stack, lo que puede ser beneficioso en entornos donde se requiere una diversidad de habilidades y experiencias técnicas.

  • ¿Qué es la estructura de monorepo y cómo NX se beneficia de ella?

    -Una estructura de monorepo es un modelo de control de versiones y gestión de código donde todos los proyectos y componentes de una organización se almacenan en un solo repositorio. NX se beneficia de esta estructura al permitir una gestión más eficiente de proyectos relacionados y la capacidad de compartir recursos y componentes entre diferentes aplicaciones, lo que puede mejorar la colaboración y la reutilización de código.

  • ¿Cómo se puede generar una aplicación Angular en un monorepo NX?

    -Para generar una aplicación Angular en un monorepo NX, se puede utilizar el comando `nx create nx-workspace@latest` y seguir los pasos interactivos para configurar el tipo de aplicación, el lenguaje de programación y otras opciones. Esto creará una nueva aplicación Angular dentro del monorepo con la configuración más reciente.

  • ¿Qué es la ventaja de tener un host application y remote applications en una estructura de micro frontend?

    -La ventaja de tener un host application y remote applications es que permite la descomposición de la aplicación en subaplicaciones manejadas por equipos independientes. Esto facilita la actualización y el desarrollo de características específicas sin afectar al conjunto mayor de la aplicación, mejorando la eficiencia y la capacidad de respuesta de los equipos de desarrollo.

  • ¿Cómo se puede utilizar un componente compartido en diferentes aplicaciones dentro de un monorepo NX?

    -Para utilizar un componente compartido en diferentes aplicaciones dentro de un monorepo NX, se puede crear una biblioteca que contenga el componente y luego exportarlo desde un archivo barrel. Luego, en las aplicaciones que requieran el componente, se puede importar directamente desde la biblioteca y utilizarlo como si fuera parte de la aplicación local.

  • ¿Qué es la configuración de Module Federation y por qué es necesaria en un micro frontend?

    -La configuración de Module Federation es un conjunto de instrucciones que define cómo las diferentes partes de una aplicación micro frontend se cargan y se comunican entre sí. Es necesaria para que las aplicaciones host y remote puedan interactuar y compartir componentes de manera efectiva, asegurando que las rutas y los enrutamientos estén correctamente configurados y que las dependencias entre las aplicaciones sean manejadas adecuadamente.

  • ¿Cómo se pueden implementar cambios en un componente compartido en un monorepo NX sin afectar otras aplicaciones?

    -Para implementar cambios en un componente compartido sin afectar otras aplicaciones, se puede utilizar CI/CD para ejecutar pruebas y validaciones específicas en las aplicaciones que utilizan el componente modificado. Esto garantiza que los cambios no causen problemas en las aplicaciones que no han sido actualizadas y permite una gestión efectiva de los cambios en un entorno de micro frontends.

  • ¿Cuáles son los desafíos y beneficios de utilizar una arquitectura de micro frontend?

    -Los beneficios de utilizar una arquitectura de micro frontend incluyen una mejor escalabilidad, la capacidad de trabajar con diferentes tecnologías y una mejor separación de responsabilidades entre equipos. Los desafíos pueden incluir la complejidad en la gestión de dependencias, la necesidad de una configuración inicial más compleja y posibles desafíos en la sincronización y colaboración entre equipos.

  • ¿Qué es la ventaja de utilizar la estructura de monorepo con NX para proyectos de desarrollo de backend?

    -La ventaja de utilizar la estructura de monorepo con NX para proyectos de desarrollo de backend es que permite la creación y gestión de aplicaciones backend, como Node.js o NestJS, en el mismo repositorio que las aplicaciones frontend. Esto facilita la integración y la colaboración entre los equipos de frontend y backend, mejorando la eficiencia y la calidad del producto final.

  • ¿Cómo se pueden generar diferentes proyectos y subaplicaciones en un monorepo NX utilizando la CLI de Angular?

    -Para generar diferentes proyectos y subaplicaciones en un monorepo NX, se puede utilizar la CLI de Angular junto con los comandos específicos de NX. Por ejemplo, se puede utilizar `nx g @nrwl/angular:module account-routing` para generar un módulo de enrutamiento y `nx g @nrwl/angular:app account-remote` para generar una subaplicación. La CLI de Angular se integra con NX para proporcionar una experiencia de desarrollo fluida y coherente.

Outlines

00:00

🚀 Introducción a micro front ends y monorepos con NX

En este primer párrafo, se presenta la temática principal del video: la exploración de micro front ends y la arquitectura de monorepos con NX. Se discute la definición de micro front end y cómo se relaciona con diferentes frameworks y librerías. Además, se menciona la ventaja de utilizar un modelo de repositorio mono (NX model repo) para organizaciones, y se anuncia que el video abordará tanto los pros y los cons de utilizar micro front end architecture.

05:01

🛠️ Configuración de un monorepo con NX y creación de aplicaciones Angular

Este párrafo detalla el proceso de configuración inicial de un monorepo con NX, incluyendo la creación de un aplicación host llamada 'Dev by Seb' y la elección de ciertos parámetros como el uso de SCSS y la habilitación de la función de enrutamiento. También se menciona la opción de habilitar la caché distribuida para acelerar el CI, y se describe el proceso de instalación de paquetes y la visualización del código en pantalla. Finalmente, se habla sobre la generación de módulos y enrutamientos dentro de la aplicación Angular.

10:02

🔄 Generación y configuración de aplicaciones host y remote en NX

En este párrafo, se aborda el tema de generar y configurar aplicaciones host y remote dentro del monorepo de NX. Se describe el problema de no haber configurado previamente un host application y se presenta la solución de generar un host con la configuración de Module Federation. Luego, se procede a crear una aplicación remote llamada 'account remote' y se explica cómo se relaciona con el host application existente. Además, se mencionan los ajustes necesarios en la configuración de webpack y se destaca la importancia de la conexión entre el host y el remote application.

15:03

🔄 Carga y uso de aplicaciones remote desde el host application

Este párrafo se centra en la carga y utilización de aplicaciones remote desde el host application. Se explica cómo el host application sirve para iniciar todos los remote applications, y se describe el proceso de configuración para que el servidor se establezca correctamente. Se muestra cómo se configura una ruta predeterminada y se destaca la facilidad de uso y la reducción de código boilerplate. Además, se aborda la posibilidad de que diferentes teams trabajen en diferentes features sin interferir entre sí, y se menciona la flexibilidad de trabajar con diferentes frameworks en remote applications.

20:06

📚 Creación y uso de componentes compartidos en NX monorepos

En este párrafo, se aborda el tema de la creación y utilización de componentes compartidos dentro de un monorepo de NX. Se describe el proceso de generar una biblioteca de componentes llamado 'button' y se explica cómo se configura para ser utilizada en diferentes aplicaciones. Se menciona la importancia de exportar el componente desde el archivo barrel para evitar problemas en las aplicaciones. Además, se muestra cómo se importa y utiliza el componente 'button' en la aplicación, y se destaca la ventaja de poder actualizar y probar componentes de forma live y aislada sin afectar otras aplicaciones.

25:08

🎉 Conclusión y recursos adicionales sobre NX monorepos y micro front ends

En el último párrafo, se concluye la presentación de cómo se establecen y trabajan con NX monorepos y micro front ends. Se menciona la facilidad de configuración con NX y Module Federation, y se hace referencia a un blog post que profundiza en los beneficios y desafíos de utilizar esta arquitectura. Se invita a los espectadores a dar su opinión y se agradece por la visualización del video.

Mindmap

Keywords

💡micro front end

El término 'micro front end' se refiere a una arquitectura en la que se desarrollan aplicaciones web como una serie de mini-aplicaciones o componentes que se integran en una sola interfaz de usuario. En el video, se discute cómo utilizar esta arquitectura con Angular y se menciona que puede ser útil para equipos con experiencias diferentes en tecnologías de desarrollo web.

💡Angular

Angular es un framework de desarrollo de aplicaciones web open-source creado por la empresa IBM y más tarde donado a la comunidad. Es conocido por su enfoque basado en componentes y su uso de TypeScript. En el video, se utiliza Angular para desarrollar aplicaciones dentro de una estructura de micro front end.

💡monorepo

Un monorepo es una única base de código que contiene múltiples proyectos relacionados, en lugar de tener un repositorio por proyecto. Este enfoque facilita la colaboración y el mantenimiento a largo plazo de código. En el video, se discute cómo utilizar un monorepo con NX, un framework de desarrollo de aplicaciones.

💡NX

NX es un framework de desarrollo de aplicaciones de código abierto creado por Palantir, que se utiliza para construir aplicaciones de tamaño empresarial. Proporciona una serie de herramientas y bibliotecas para ayudar a los desarrolladores a trabajar en proyectos de gran envergadura. En el video, se utiliza NX para construir y gestionar aplicaciones con arquitecturas de micro front end.

💡Module Federation

Module Federation es una característica de webpack que permite que diferentes aplicaciones web compartan código y módulos de terceros de forma más eficiente. Esta técnica es útil para la implementación de arquitecturas de micro front end, donde varias aplicaciones pueden ser servidas y actualizadas independientemente. En el video, se explora cómo utilizar Module Federation con Angular y NX.

💡arquitectura de micro front end

La arquitectura de micro front end es un enfoque para el desarrollo de aplicaciones web en el que la aplicación se construye como una colección de mini-aplicaciones o componentes más pequeños y autónomos. Cada una de estas mini-aplicaciones puede ser desarrollada,部署 y actualizada de forma independiente. Esta arquitectura es especialmente útil para proyectos de gran envergadura con múltiples equipos de trabajo.

💡React

React es un biblioteca y un enfoque de programación declarativa para construir interfaces de usuario, creado por Facebook. Es conocido por su enfoque en la creación de componentes reutilizables y su eficiencia en la renderización de aplicaciones web. En el video, se sugiere que React podría ser una buena opción para aplicaciones medianas o pequeñas.

💡webpack

Webpack es un sistema de módulos de JavaScript y un bundler que permite a los desarrolladores empaquetar y minimizar el código de sus aplicaciones para su distribución en la web. Es una herramienta común en el desarrollo web moderno, especialmente útil para la gestión de dependencias y la optimización de recursos estáticos. En el video, webpack es mencionado como parte de la configuración de Module Federation.

💡Node.js

Node.js es un entorno de ejecución de JavaScript que permite a los desarrolladores escribir código del lado del servidor en JavaScript, en lugar de lenguajes como PHP o Ruby. Con Node.js, es posible aprovechar la eficiencia y la capacidad de JavaScript para crear aplicaciones web completas. En el video, se sugiere que NX puede ser utilizado para desarrollar aplicaciones back-end con Node.js y integrarlas en un monorepo.

💡CI/CD

CI/CD son las siglas en inglés de 'Integración Continua' (Continuous Integration) y 'Despliegue Continuo' (Continuous Deployment). Estas prácticas forman parte de la cultura de desarrollo de software moderno y permiten a los equipos de desarrollo integrar y lanzar código de manera rápida y confiable. En el video, se hace referencia a cómo la arquitectura de micro front end y las herramientas de NX pueden facilitar la implementación de CI/CD.

💡library

Una 'library' en el contexto de desarrollo web se refiere a una colección de componentes o funciones reutilizables que pueden ser importados en diferentes aplicaciones. Estas bibliotecas permiten a los desarrolladores evitar la duplicación de código y mantener una consistencia en la implementación de características a través de múltiples proyectos. En el video, se discute cómo crear y utilizar bibliotecas en un monorepo de NX.

Highlights

Introduction to monorepo structure with NX and its benefits for organizations.

Exploration of micro frontend architecture and its use cases.

Comparison of different programming frameworks and libraries for various application sizes and team experiences.

Demonstration of using Module Federation with Angular applications.

Explanation of the advantages of having a single front-end project within a monorepo in NX.

Step-by-step guide on generating a new workspace with NX and choosing configurations.

How to create an integrated monorepo application with routing and distributed caching options.

Process of generating a remote application within the monorepo and setting up the necessary configurations.

Utilizing the NX console for generating modules and managing the application structure.

Explanation of how micro frontends can be served and loaded within the host application.

Demonstration of creating a shared component library and its usage across different applications.

Importing and using the shared button component in both host and remote applications.

The benefits of using micro frontend architecture for large enterprise applications with multiple teams working on different features.

How NX enforces a mental model for creating libraries and avoiding logic within applications.

The ease of setting up micro frontends with NX and Module Federation.

Conclusion on the practical applications and impact of using NX monorepos and micro frontend architecture.

Transcripts

play00:00

hello and welcome to this video guys

play00:02

today we're going to look into mono

play00:03

repos with NX we're also going to look

play00:05

into microphone tents different ways of

play00:08

approaching the micro fronted

play00:09

architecture with angular we're also

play00:12

going to look into pros and cons of

play00:14

using microfront and architecture and

play00:16

also why using a NX model repo is a good

play00:21

structure for your organization and so

play00:23

on so let's get started

play00:25

all right so let's get started with two

play00:27

different concepts that we're going to

play00:29

look into so the first thing would be

play00:30

the micro front end what is a micro

play00:32

front end and how should we think about

play00:35

it so to continue working with this

play00:37

let's investigate what a micro front end

play00:40

really is so looking at this image here

play00:42

you can see we have different

play00:44

applications or micro applications that

play00:47

is being served at the same time in

play00:50

different Frameworks or libraries

play00:53

in the same view right so this is

play00:55

something that could be achievable with

play00:58

module Federation for instance there's a

play01:00

couple of other Alternatives as well but

play01:03

in this video we're going to look into

play01:04

model Federation and we're also only

play01:07

going to focus on angular applications

play01:08

in this video

play01:10

so in short you can deploy each and one

play01:15

of these application individually so for

play01:18

instance they might grab one here at the

play01:20

top Minecraft one so this would probably

play01:22

be the host application so the react

play01:25

part and then within that host

play01:27

applications you would have remote

play01:29

applications

play01:32

so the remote applications in this case

play01:34

could be for instance you have some

play01:36

content calendar logic being visualized

play01:39

in angular you could have a couple of

play01:41

other features in in view or swelt the

play01:44

reason to why you want to have it in

play01:46

this way where you can have different

play01:47

variants of program programming

play01:50

Frameworks and libraries is usually due

play01:54

to teams having different experiences so

play01:57

I I would say that having four different

play02:00

Frameworks or libraries would be Madness

play02:02

in my in my case or my opinion I would

play02:05

say having maybe two would be good

play02:08

enough I mean react to Wrangler I would

play02:11

have them for complete standalone

play02:14

and differences I think they they might

play02:16

be used in different aspects of

play02:19

development so for Enterprise

play02:21

applications I would say angular the

play02:23

want to go react would be maybe small to

play02:26

medium sized applications where you

play02:28

don't have too much logic where you want

play02:31

to enforce a certain structure right so

play02:34

there's where when I would use react but

play02:36

in terms of this video we're only going

play02:38

to look into uh the angular applications

play02:43

so the next concept we have is a mono

play02:47

Ripple structure with NX so what is a

play02:50

monos Repro structure so mono stands for

play02:53

one

play02:55

um in and working with different

play02:57

applications in organizations might be

play03:01

that in front end you would have

play03:03

multiple repositories for different

play03:05

applications which is quite common but

play03:08

with NX model repo you would have every

play03:10

single front-end project or essentially

play03:13

backing with node with nest and so on

play03:17

within the same repository there is a

play03:20

lot of benefits having them in the same

play03:22

repository there it's also

play03:24

pros and cons with everything but I

play03:26

would say that the pros outruns the cons

play03:30

in this case so as you can visualize

play03:32

here we would have all of these

play03:34

applications within the same

play03:36

GitHub repository I'm working with the

play03:40

NX monorip so let's get started so in

play03:43

order to get started with this NX mono

play03:44

Ripple Fuller structure we're going to

play03:46

utilize the command that that is given

play03:49

by the NX and also keep in mind that

play03:51

this works for react View and angular so

play03:53

you can choose pick and choose what you

play03:55

want you can also place your component a

play03:57

library here which would be generated

play03:59

with for instance web components in

play04:02

stencil.js or lib.js to generate

play04:06

components that could be utilized in

play04:08

different Frameworks but today the focus

play04:10

is going to be angry

play04:12

so just pasting the mpxcrate NX

play04:15

workspace at latest so it will generate

play04:17

a complete new workspace for us with the

play04:19

latest configurations let's proceed

play04:23

um would you like to create your own

play04:25

create your workspace just press enter

play04:27

and here you can choose do you want to

play04:30

have typescript Js or what you want

play04:31

we're going to choose angular keep in

play04:34

mind you can also place your backend

play04:36

applications here so it's not only for

play04:38

front-end this is the benefit of using

play04:39

NX for instance if you're working with a

play04:41

node backend as you can see as you might

play04:44

see here in in the bottom of the screen

play04:47

uh node you can generate node

play04:50

applications or Nest applications it

play04:52

could be applications where you run your

play04:54

backend and you can combine them in an

play04:57

easy way because they live in the same

play04:58

Repository

play05:00

all right so let's continue we're

play05:01

generating an angular application

play05:04

um

play05:06

we're going to create an integrated

play05:07

monorepo

play05:10

application name so let's call it Dev by

play05:13

Seb

play05:15

host

play05:17

we're going to use scss

play05:20

we would like to use Standalone

play05:22

components but let's not do that right

play05:24

now we want to use routing yes either

play05:27

here you can choose if you want to have

play05:29

enabled distributed caching to make your

play05:31

CI faster this will be connected to the

play05:33

NX Cloud for this com case that we have

play05:36

today I'm going to choose no

play05:38

so now it's going to install a couple of

play05:40

different packages we have

play05:42

let's see here

play05:44

let's also make the screen a bit bigger

play05:46

so we can explore the

play05:49

code together

play05:54

all right so this might take a couple of

play05:56

seconds we will be right back once this

play05:59

is up and running

play06:00

so in order for us to get started we can

play06:02

either click on this link here or just

play06:03

navigate to localhost 4200 in order for

play06:06

us to get started to the application you

play06:09

can also go to the app uh component file

play06:12

just clean this up a bit we're going to

play06:13

remove the um the NX welcome component

play06:16

that we receive not interested so let's

play06:19

just go ahead and remove that real quick

play06:21

and we're also removing it from the

play06:25

from aerosol all right so once we have

play06:29

essentially removed that now it should

play06:31

be up and running we have the routes

play06:33

here so if you want to generate a route

play06:35

we can do it so if you have installed

play06:37

the NX console you can just right click

play06:39

and you can go with NX generate here you

play06:41

can see I want to generate a module so

play06:44

schematic slash angular module it will

play06:46

utilize that to generate it so we can

play06:48

just say account

play06:51

so let's see here

play06:54

we could

play06:56

let's see here route

play06:58

create the routing module let's say we

play07:00

want to have sub routes and so on so

play07:02

let's go ahead and just generate real

play07:03

key real quick and you'll see what

play07:05

happens

play07:06

um and as you can see here we have the

play07:08

account module with a routing module

play07:10

quite similar to the way you would do it

play07:12

in the with the angular CLI this

play07:14

essentially just utilizes the angular

play07:16

CLI map

play07:17

all right so now we have a module you

play07:20

can just add a route in which way you

play07:23

want it to be added so let's say we want

play07:24

to generate a new applications

play07:27

you can just go to NX you can go to

play07:29

generate and then you would say I want

play07:31

to generate a shell application so

play07:34

from from before you have the host

play07:36

application with it which is essential

play07:38

the application we created here the

play07:40

localhost running on locals 4 200 and

play07:43

then we have the shell application that

play07:45

we now are going to generate and this is

play07:47

going to be a sub application that we

play07:51

place within our application it could be

play07:53

for instance the the account module in

play07:55

this case

play07:56

all right so let's let's click on that

play07:59

we can see what we want the project to

play08:01

be named at

play08:03

um

play08:03

let's see here can make the screen a bit

play08:06

bigger uh we want it so we need to point

play08:11

which is the related Client app which is

play08:13

essentially the host application that we

play08:15

have

play08:16

um the ID let's see here which is the

play08:19

main server file and so on

play08:22

um all right so let's generate this and

play08:24

see what happens

play08:31

so let's open the console

play08:36

so we need to have a router applet in

play08:39

our root component so let's go ahead and

play08:41

just add that and we can just regenerate

play08:46

um so it's it's super tactile it will

play08:49

usually give you the exact

play08:51

thing you need to do in order to proceed

play08:53

so now that we have the router module it

play08:56

will automatically set up a different

play08:58

kind of structure for us all right so if

play09:01

I now open up let's see what happened

play09:04

um

play09:09

so here we need to generate the go to NX

play09:13

generate and here we're going to select

play09:14

a remote application so we want to

play09:16

generate a remote application here we

play09:18

want to name it let's call it account

play09:21

and then we're going to specify which is

play09:24

the host which is going to be the one we

play09:26

generated before so continuing there's a

play09:29

couple of things we can we can add

play09:30

tailwind and so on we're not going to do

play09:32

that we want Cyprus to be the test thing

play09:34

we're going to use the eslint

play09:36

and here you can decide like if you want

play09:39

to have server side rendering and so on

play09:41

which I do not want we're going to use

play09:43

scss

play09:44

um

play09:45

all right so now that we have everything

play09:47

set up we can just generate this

play09:50

application now

play09:51

and it's going to generate a sub

play09:53

application and here it will give some

play09:55

complaints to us

play09:57

um the selected it does not contain a

play10:00

modifier Federation to ensure it has

play10:02

been set up as a host application and

play10:04

the issue is that we did not really set

play10:05

up a host application as a starters we

play10:08

just generated a default angular

play10:10

application so what we need to do now is

play10:13

essentially we need to generate the host

play10:15

so we're going to

play10:16

generate the host and this is going to

play10:19

include the

play10:20

um the module Federation so we'll call

play10:23

it host

play10:24

just call it host for now it doesn't

play10:26

really matter we can

play10:28

at the same time we're generating it in

play10:30

this way we could probably let's see

play10:32

here

play10:33

let's just generate it let's make sure

play10:36

we have all of the configurations we

play10:39

wanted to have a CSS and so on so

play10:42

generated all right so it will generate

play10:44

a new application obviously we need to

play10:45

remove the old one because we're yeah

play10:47

because it requires the model Federation

play10:51

config this is the file I was missing

play10:53

before so this is the file in in which

play10:56

it asks for so and it also has the

play10:59

webpack prod config and webcam pack

play11:01

config so let's just go ahead and remove

play11:03

these two applications that we yeah

play11:05

obviously we need to stop this

play11:08

we can

play11:10

we're going to delete them we're just

play11:12

going to ignore them uh we generate now

play11:14

a remote application so generate search

play11:18

for remote

play11:19

and here we can specify our host and

play11:21

this is going to be let's call it

play11:22

account

play11:24

remote

play11:26

the name standards obviously should

play11:28

follow whatever you have in your

play11:29

organization maybe it would just be

play11:31

account module and so on this is

play11:33

something you would have to decide with

play11:34

Architects and so on

play11:36

um all right so now that we have

play11:38

generated the remote application we

play11:40

should have one remote application and

play11:42

one host application right so

play11:45

and you will see here that the remote

play11:48

DTS is just typing for the remotes

play11:50

module

play11:51

um you'll not be able to remove this if

play11:53

you remove this it won't work as you

play11:54

want it looking into the modern

play11:56

Federation config file you'll see that

play11:58

account Remote application is part of

play12:01

the remote application you'd also see

play12:03

that

play12:05

um

play12:05

sorry if you go to the webpack config

play12:07

file we have pointing towards the model

play12:10

Federation config file so this is why

play12:13

it's required

play12:16

um and also if you want to have some

play12:18

other webpack configurations you could

play12:19

add them here to the product config.js

play12:22

file

play12:23

we're not going to look into that so now

play12:25

that we have we have a host and a remote

play12:28

application so what we want to do

play12:29

essentially see how can we load in one

play12:33

application from the other application

play12:34

right

play12:35

so it will just serve it uh we're going

play12:38

to serve the host application

play12:42

um the reason to why you want to serve

play12:43

the host applications is because that

play12:45

this one should spin up all of the uh

play12:48

the remote applications as well

play12:52

and as you can see here it it spins up

play12:54

the account built for development and it

play12:57

also will serve the the host application

play13:00

that you have as well so allowing it a

play13:03

couple of seconds you will be able to

play13:04

just navigate to let's see here I think

play13:07

4200 see what will happen

play13:10

let's see

play13:14

so it will set up a server for you and

play13:16

you can see home and account remote so

play13:18

it already has set up a route for you

play13:21

which is quite awesome because then

play13:22

there's a lot of boilerplate code you

play13:24

don't need to Rob uh read so if you go

play13:26

to approach keep in mind we want to go

play13:28

to the hosts Source app not the account

play13:31

remote and here you can see how it

play13:33

actually loads the children in a similar

play13:36

way you would load a lazy load feature

play13:39

module right

play13:40

so this is quite awesome because now you

play13:44

already have a connection between the

play13:46

host and the remote application so for

play13:49

instance when we jump here it goes from

play13:51

the host to the remote and let's jump

play13:53

into the NX

play13:55

component here and just

play13:58

remove all of this scrap and just add

play14:00

router Outlet

play14:02

and then

play14:03

sorry this nothing should be added there

play14:06

I just reckoned hello world just print

play14:08

hello world there instead so we'd go

play14:10

home and you would have your application

play14:12

here so

play14:14

it would be in a similar way so if you

play14:16

would want to have any logic on the app

play14:18

route

play14:19

um

play14:20

for the host application you just place

play14:23

it in a similar routing way as you would

play14:26

do in a regular angle application we do

play14:28

not want that we want it straight to

play14:29

jump onto the remote module because we

play14:32

do not have anything or we don't have

play14:34

really anything placed within the the

play14:36

the app component in front of so if I go

play14:39

to that component to imagine it would

play14:41

have a menu here right so this is the

play14:42

menu as you can see and

play14:45

what happens is that it actually loads

play14:48

the remote applications from the router

play14:50

Outlet so this would be in a similar way

play14:53

as you would be used to working with the

play14:56

regular angle application so if I now

play14:58

would go to the other applications that

play14:59

I have uh you would see that I can go to

play15:03

the sorry if I go to the to here's the

play15:05

remote entry so keep in mind it all it

play15:08

always points towards a certain module

play15:10

right so the entry module remote entry

play15:12

module in this case and you can change

play15:14

the name of it you can do whatever you

play15:16

want with it you can point towards

play15:17

another feature and so on but we're not

play15:20

going to look into that too much

play15:22

so let's just clean up all of this code

play15:26

that comes from NX we're not really

play15:28

interested in it

play15:29

my remote application

play15:32

so if I save this now jumping between

play15:34

home and the remote application it

play15:37

should give us a couple of different

play15:39

things and as you can see here it does

play15:41

not really reload this sub applications

play15:45

because we decided to run it from the

play15:48

app component TS file so

play15:52

let's see here compile successful it

play15:55

doesn't really recompile the sub

play15:59

features that you have so you would have

play16:00

to set up a different way of working

play16:02

with it

play16:03

usually the way you would work with the

play16:06

sub application is that you would just

play16:08

go serve account and then you would just

play16:10

serve your account Remote application to

play16:13

do the changes there this means that

play16:16

Standalone teams can work on different

play16:18

features at the same time without having

play16:21

to think of destroying other

play16:23

applications obviously we can destroy

play16:24

the host applications by adding strange

play16:27

logic but now we can go to 4201 and we

play16:31

can continue to actually implement the

play16:33

logic we want to have on the remote

play16:35

application

play16:37

so this my friends is one way of

play16:39

actually working with micro front ends

play16:43

so you might think how is this

play16:44

beneficial why would I really have the

play16:46

micro front end architecture and I would

play16:48

say if you do not think you need it then

play16:51

you obviously don't need it right do not

play16:53

make things over complicated for no

play16:56

reason you would only need to have Micro

play16:58

front ends if you have a super large

play17:01

Enterprise applications where you have

play17:03

multiple teams working on sub features

play17:05

without having to just like ruin

play17:08

anything in between the applications so

play17:11

for instance if I work on the account

play17:12

module and someone works on a complete

play17:14

separate feature we do not want we want

play17:17

to be able to deliver our feature

play17:19

without having to wait for things in

play17:22

other applications

play17:24

um so with this said you can have

play17:27

complete Standalone teams working on

play17:29

features together but also keep in mind

play17:31

that working with micro for instance and

play17:33

model Federation also allows you to work

play17:36

with different Frameworks for instance

play17:37

my remote application in this

play17:41

application could for instance be set up

play17:43

with react it does not really need to be

play17:46

an angular application

play17:47

so there's actually different ways you

play17:50

can utilize the micro front ends to have

play17:53

different teams working in different

play17:54

stacks and so on we're not going to

play17:57

explore this as for now I just want to

play17:59

show one last thing on on how you could

play18:02

work with libraries so NX enforces

play18:04

something they call a mental model that

play18:07

is that usually create libraries and you

play18:10

do not put so much logic within the

play18:12

actual applications which makes total

play18:14

sense when you work with it for for some

play18:17

time in the beginning it might be a bit

play18:19

confused but let's look into a library

play18:21

so

play18:22

let's say we want to create a shared

play18:26

button component that would be used in

play18:29

the different applications so both in

play18:31

the remote application and and the host

play18:33

application

play18:35

so generate it so let's call it button

play18:38

we're not going to think about any

play18:40

directory we're not going to think about

play18:42

anything else like that we're just going

play18:44

to make it quite simple and you guys

play18:46

decide on how your organization would

play18:48

need it to be done so let's let's go

play18:52

ahead and create it with cscss so now

play18:55

when I generate it it will generate a

play18:58

library which will consist of the

play19:01

um

play19:01

it will not consist of anything for us

play19:03

for now but we need to

play19:05

create some data so if we just close the

play19:07

apps folder there's also ellipse folder

play19:10

and as you can see here it has generated

play19:12

one library for us and now we can

play19:15

generate within the lib here we can

play19:16

generate a component we could have it

play19:18

Standalone but we do not want it to be

play19:20

just for this purpose to just simulate

play19:23

how it would work now we can generate a

play19:25

component within the library

play19:28

so we're going to generate the button

play19:30

component which is going to be utilized

play19:31

in both both the host and remote

play19:34

application

play19:35

so one thing to keep in mind is that you

play19:37

need to export it from the barrel

play19:39

function sorry the barrel file otherwise

play19:42

you might have some problems in your

play19:44

applications so

play19:48

what what do we want to do we are going

play19:50

to look into a couple of different

play19:51

things

play19:53

all right so if you now go to the TS

play19:55

config base file you should see that the

play19:58

button or the library that we just

play20:00

generated should have some sort of a

play20:02

path setup so if you want to import the

play20:05

button module we would import it in this

play20:07

way or if we wanted to to import the

play20:09

button component we would import it from

play20:11

it so for now we have a similar way of

play20:16

working with angular so you have Imports

play20:17

declaration exports just as a module

play20:20

right

play20:22

and in the button let's just go ahead

play20:24

and and do it real simple and ugly right

play20:28

we're going to transfloat whatever we

play20:30

have we're going to have a button we can

play20:32

just add a style to it let's make the

play20:34

button black

play20:35

and keep in mind this is just exactly

play20:38

the same on how you would use a

play20:40

component in in angular otherwise

play20:43

um

play20:43

so let's see here we generate a button

play20:47

black white color and zero border let's

play20:51

add some padding so go ahead and say

play20:53

padding top button for PX 20px to the

play20:57

sides now that we have the button

play20:59

component we can make sure that we

play21:01

import it right so in we go back to our

play21:04

application and currently we are

play21:06

essentially serving the micro front end

play21:10

let's see here we will shrink the screen

play21:12

a bit

play21:14

so we have the my remote application

play21:16

we're serving it for now

play21:19

so what can we do we can save it go to

play21:22

the HTML

play21:23

we can close all the files let's make

play21:25

sure that you can see the name of the

play21:27

files as well might

play21:29

make total total sense so now we need to

play21:32

navigate to the add account remote

play21:34

module let's go to the app module there

play21:37

we are going to import the button module

play21:42

and as you can see it is being imported

play21:45

from org slash button this comes from

play21:48

the TFS config base file you can change

play21:51

it to whatever you want it to be usually

play21:53

it would be your organization and then

play21:55

the name of the library

play21:57

all right so now that we have imported

play22:00

it we could essentially go to the

play22:02

um NX welcome component and we can say

play22:05

let's see order button

play22:08

oops or a button

play22:12

let's see here what did we name it it's

play22:15

going to be org button did we make sure

play22:18

that it was imported in the correct

play22:20

module sorry it needs to be imported in

play22:22

the entry module obviously because

play22:24

that's where it is

play22:26

or essential thenx component lives so

play22:29

now that I've imported it the button

play22:31

should be here we can see my button

play22:34

so saving this we should have the up the

play22:37

button to the right and as you can see

play22:39

now we have one button being served on

play22:41

the remote application and now if I go

play22:44

to the button you should be able to see

play22:46

live updates so just imagine if you have

play22:49

hundreds of projects maybe you would not

play22:52

have that many but if you would have a

play22:54

complete set of applications that you

play22:56

have and you want to make some changes

play22:59

to a common component that would be a

play23:02

complete mess right but utilizing the

play23:05

microphone and architecture you can

play23:08

Implement some smart CI CD essentially

play23:11

testing

play23:12

all of the different places where the

play23:15

applications are being being used so

play23:18

this is something that NX already has

play23:20

built in so you would have the affected

play23:23

and here you can say I want to run all

play23:26

of the affected projects that has been

play23:29

impacted by this change and I want to

play23:32

run the lint or I want to run the

play23:33

entrance test for it and so on just

play23:36

imagine what would happen now we only

play23:38

have this button within the remote

play23:40

application

play23:42

which would trigger the remote

play23:44

application to be tested and so on in

play23:46

the CI CD pipeline but let's take a step

play23:50

back we have utilized it in one

play23:52

application now we want to utilize it in

play23:53

the host application as well so what we

play23:56

need to do there is quite similar we

play23:57

import the button module here as well

play24:00

and after importing the button module

play24:02

let's see here

play24:04

and let's see app component

play24:08

and here we can just say I want to add

play24:10

the org button right so

play24:13

my host button so as I'm not really

play24:17

running the host application we can run

play24:19

the host application at the same time in

play24:21

test mode and you can do that by

play24:23

actually going to serve host and it will

play24:25

execute it in this way and let's just go

play24:27

ahead and close the other applications

play24:29

that we have running

play24:32

um let's see here it's essentially going

play24:34

to run both of them and we should have

play24:37

two different buttons being previewed

play24:39

and then we know for a fact that we have

play24:42

something reusable

play24:46

right so give it a couple of seconds

play24:48

maybe we need to navigate to Four sorry

play24:50

four thousand two hundred in order for

play24:52

us to actually hit the host application

play24:54

and then we have my host button and then

play24:56

we have my button which actually comes

play24:58

from the account remote module

play25:00

all right guys

play25:01

all right guys now that we have

play25:03

demonstrated on how it works with NX

play25:05

monorepos and other Federation we can we

play25:07

can conclude a couple of things it's

play25:09

quite easy to set this up with NX and

play25:12

model Federation

play25:14

um but there's also a couple of other

play25:15

pros and cons of actually utilizing NX

play25:18

model repos and that's something I've

play25:20

written a bit about in my blog post so

play25:23

understanding microfrontal architecture

play25:25

benefits and challenges I'm going to

play25:27

drop that link in that in in the

play25:30

comments or in the description of this

play25:32

video please have a look uh give me your

play25:34

take on it I would appreciate any

play25:37

positive or negative feedback and thank

play25:40

you guys for watching all of the best

play25:42

bye

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
ArquitecturaMicroFrontendsModelFederationNXMonorepoDesarrolloAngularEstructuraProyectosEstablecimientoEquiposDinámicaColaborativaOptimizaciónProcesosPruebasContinuasDespliegueApps