Skip to content

Commit

Permalink
Revert "docs(angular): update the mfe guide (#9478)" (#9492)
Browse files Browse the repository at this point in the history
This reverts commit 09ad5ff.
  • Loading branch information
Coly010 committed Mar 24, 2022
1 parent 53799ef commit 1903f01
Showing 1 changed file with 72 additions and 25 deletions.
97 changes: 72 additions & 25 deletions docs/shared/guides/setup-mfe-with-angular.md
Expand Up @@ -3,13 +3,13 @@
[Webpack 5](https://webpack.js.org/blog/2020-10-10-webpack-5-release/) introduced a [Module Federation Plugin](https://webpack.js.org/concepts/module-federation/#modulefederationplugin-high-level) enabling multiple, independently built and deployed bundles of code to form a single application. This is the foundation of Micro Frontend Architecture and the Module Federation Plugin makes implementing such an architecture much simpler.
With Angular 12 adding support for Webpack 5 it increases the viability of scaffolding a Micro Frontend architecture with Angular.

We have added some generators to aid in the scaffolding of Module Federation configuration required for setting up a Micro Frontend Architecture.
We made some changes to our `@nrwl/angular:app` generator to aid in the scaffolding of Module Federation configuration required for setting up a Micro Frontend Architecture.

Therefore, using Nx, it can be fairly straightforward to scaffold and build a Micro Frontend Architecture from a monorepo with all the additional benefits of Nx.
Therefore, using Nx it can be fairly straightforward to scaffold and build a Micro Frontend Architecture from a monorepo with all the additional benefits of Nx.

In this guide, we'll show you to how setup a Micro Frontend Architecture with Nx and Angular.

_**NOTE:** When serving MFEs in dev mode locally, there'll be an error output to the console: `import.meta cannot be used outside of a module`, and the script that is coming from is `styles.js`. It's a known error output, but it doesn't actually cause any breakages from as far as our testing has shown. It's because the Angular compiler attaches the `styles.js` file to the `index.html` in a `<script>` tag with `defer`.
_NOTE: When serving MFEs in dev mode locally, there'll be an error output to the console, `import.meta` cannot be used outside of a module, and the script that is coming from is `styles.js`. It's a known error output, but it doesn't actually cause any breakages from as far as our testing has shown. It's because the Angular compiler attaches the `styles.js` file to the `index.html` in a `<script>` tag with `defer`.
It needs to be attached with `type=module`, but doing so breaks HMR. There is no way of hooking into that process for us to patch it ourselves.
The good news is that the error doesn't propagate to production, because styles are compiled to a CSS file, so there's no erroneous JS to log an error.
It's worth reiterating that there's been no actual errors or breakages noted from our tests._
Expand Down Expand Up @@ -68,34 +68,39 @@ Simple! You are now able to use Nx Generators to scaffold Angular applications a

### Creating our apps

We need to generate two applications that support Module Federation.
We need to generate two applications. We also need to tell Nx that we want these applications to support Module Federation.

We'll start with the Admin Dashboard application which will act as a host application for the MFE:

```bash
# Npm
npx nx g @nrwl/angular:host dashboard
npx nx g @nrwl/angular:app dashboard --mfe --mfeType=host --routing=true
```

```bash
# Yarn
yarn nx g @nrwl/angular:host dashboard
yarn nx g @nrwl/angular:app dashboard --mfe --mfeType=host --routing=true
```

The application generator will create and modify the files needed to setup the Angular application.
You'll be prompted for some additional options. For this tutorial, just select the default options.
The application generator will create and modify the files needed to setup an Angular application.

Now, let's generate the Login application as a remote application.

```bash
# Npm
npx nx g @nrwl/angular:remote login --host=dashboard
npx nx g @nrwl/angular:app login --mfe --mfeType=remote --port=4201 --host=dashboard --routing=true
```

```bash
# Yarn
yarn nx g @nrwl/angular:remote login --host=dashboard
yarn nx g @nrwl/angular:app login --mfe --mfeType=remote --port=4201 --host=dashboard --routing=true
```

_**Note:** We provided `remote` as the `--mfeType`. This tells the generator to create a Webpack configuration file that is ready to be consumed by a Host application._

_**Note:** We provided `4201` as the `--port`. This helps when developing locally as it will tell the `serve` target to serve on a different port reducing the chance of multiple remote apps trying to run on the same port._

_**Note:** We provided `--host=dashboard` as an option. This tells the generator that this remote app will be consumed by the Dashboard application. The generator will automatically link these two apps together in the `webpack.config.js`_

_**Note**: The `RemoteEntryModule` generated will be imported in `app.module.ts` file, however, it is not used in the `AppModule` itself. This it to allow TS to find the Module during compilation, allowing it to be included in the built bundle. This is required for the Module Federation Plugin to expose the Module correctly. You can choose to import the `RemoteEntryModule` in the `AppModule` if you wish, however, it is not necessary._
Expand All @@ -113,39 +118,70 @@ For both apps, the generator did the following:
- Changed `main.ts` to dynamically import `bootstrap.ts` _(this is required for the Module Federation to correct load versions of shared libraries)_
- Updated the `build` target in the `project.json` to use the `@nrwl/angular:webpack-browser` executor _(this is required as it supports passing a custom webpack configuration to the Angular compiler)_
- Updated the `serve` target to use `@nrwl/angular:webpack-server`. _(this is required as we first need webpack to build the app with our custom webpack config)_
- Installed Manfred Steyer's `@angular-architects/module-federation` package _(Read more on it [here](https://github.com/angular-architects/module-federation-plugin))_

The key differences reside within the configuration of the Module Federation Plugin within each app's `webpack.config.js`.

We see the following within Login's webpack configuration:

```js
const { withModuleFederation } = require('@nrwl/angular/module-federation');
module.exports = withModuleFederation({
new ModuleFederationPlugin({
name: 'login',
filename: 'remoteEntry.js',
exposes: {
'./Module': 'apps/login/src/app/remote-entry/entry.module.ts',
},
});
shared: {
'@angular/core': { singleton: true, strictVersion: true },
'@angular/common': { singleton: true, strictVersion: true },
'@angular/common/http': { singleton: true, strictVersion: true },
'@angular/router': { singleton: true, strictVersion: true },
...sharedMappings.getDescriptors(),
},
library: {
type: 'module',
},
}),
```

Taking a look at each property of the configuration in turn:

- `name` is the name that Webpack assigns to the remote appliction. It **must** match the name of the application.
- `name` is the name that Webpack assigns to the remote appliction. It usually matches the name of the application.
- `filename` is the name given to the remote entrypoint that Webpack sets up to allow shell applications to consume the remote application.
- `exposes` is the list of source files that the remote application provides consuming shell applications for their own use.
- `shared` is a list of libraries that should be shared between the remote and the shell application. By setting `singleton: true` we ensure that Webpack will only provide one instance of the library across the shell application and the remote application.

_**NOTE:** You may have some concerns that `remoteEntry.js` is not hashed as it could potentially lead to caching issues. This can be easily rectified with [ETags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag). ETags are supported by a lot of hosting providers and servers with some ETagging static assets by default._

We can see the following in Dashboard's webpack configuration:

```js
const { withModuleFederation } = require('@nrwl/angular/module-federation');
module.exports = withModuleFederation({
name: 'dashboard',
remotes: ['login'],
});
new ModuleFederationPlugin({
remotes: {
login: 'http://localhost:4201/remoteEntry.js',
},
shared: {
'@angular/core': { singleton: true, strictVersion: true },
'@angular/common': { singleton: true, strictVersion: true },
'@angular/common/http': { singleton: true, strictVersion: true },
'@angular/router': { singleton: true, strictVersion: true },
...sharedMappings.getDescriptors(),
},
library: {
type: 'module',
},
}),
```

The key difference to note with the Dashboard's configuration is the `remotes` array. This is where you list the remote applications you want to consume in your host application.
The key difference to note with the Dashboard's configuration is the `remotes` object. This is where you list the remote applications you want to consume in your host application.

You give it a name that you can reference in your code, in this case `login`. Nx will find where it is served.
You give it a name that you can reference in your code, in this case `login`.
Then you assign it a string value of the following pattern:
`{url}/{remoteEntrypointFilename}`
where:

- `url` is the url where the remote application is hosted
- `remoteEntrypointFilename` is the filename supplied in the remote's webpack configuration

Now that we have our applications generated, let's move on to building out some functionality for each.

Expand All @@ -155,7 +191,7 @@ We'll start by building the Login app, which will consist of a login form and so

### User Library

Let's create a user data-access library that will be shared between the host application and the remote application. This will be used to determine if there is an authenticated user as well as providing logic for authenticating the user.
Let's create a user data-access library that we will share between the host application and the remote application. This will be used to determine if there is an authenticated user as well as providing logic for authenticating the user.

```bash
nx g @nrwl/angular:lib shared/data-access-user
Expand Down Expand Up @@ -321,10 +357,20 @@ Perfect! Our login application is complete.

Now let's create the Dashboard application where we'll hide some content if the user is not authenticated. If the user is not authenticated, we will present them with the Login application where they can log in.

For this to work, the state within `UserService` must be shared across both applications. Usually with Module Federation in webpack, you have to specifiy the packages to share between all the apps in your Micro Frontend solution.
However, by taking advantage of Nx's project graph, Nx will automatically find and share the dependencies of your applications.
To make this work, however, there are some initial steps we need to take. We need the state within `UserService` to be shared across both applications. To do this, we need to add a mapping within each application's `webpack.config.js` file.

Open up each and replace the `sharedMappings` config _(found near the top)_ with the following:

_**Note:** This helps to enforce a single version policy and reduces the risk of [Micro Frontend Anarchy](https://www.thoughtworks.com/radar/techniques/micro-frontend-anarchy)_
```js
sharedMappings.register(
tsConfigPath,
[
/* mapped paths to share */
'@ng-mfe/shared/data-access-user',
],
workspaceRootPath
);
```

Now, let's delete the `app.component.html` and `app.component.css` files in the Dashboard app. They will not be needed for this tutorial.

Expand Down Expand Up @@ -377,9 +423,10 @@ nx run dashboard:serve-mfe

As you can see, with this approach, your Login application can be deployed independently and developed independently without forcing you to have to rebuild or redeploy your Dashboard application. This can lead to a powerful micro frontend architecture that enables multiple teams to work independently in a single monorepo!

In this tutorial, we exposed a single module that was consumed dynamically as an Angular Route.
In this tutorial, we exposed a single module that was consumed dynamically as an Angular Route. You can see how that is done in more detail in [Manfred Steyer's](https://twitter.com/ManfredSteyer) article on Micro Fontends [here](https://www.angulararchitects.io/en/aktuelles/the-microfrontend-revolution-part-2-module-federation-with-angular/).

## References and Further Reading

- Module Federation: https://webpack.js.org/concepts/module-federation/
- Mirco Frontend Revolution Article Series: https://www.angulararchitects.io/aktuelles/the-microfrontend-revolution-module-federation-in-webpack-5/
- Repo containing the code in this example: https://github.com/Coly010/ng-mfe-example

1 comment on commit 1903f01

@vercel
Copy link

@vercel vercel bot commented on 1903f01 Mar 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.