Steps to adopt micro frontends architecture for your frontend application in Angular
Hardique Dasore
Posted on March 10, 2023
If you have an Angular project with a mono repo that is shared among various teams, you should consider changing the monolithic architecture of your application to micro-frontends using module federation.
1 Create an nx-worspace using:
npx create-nx-workspace@latest <project name>
• Select angular and scss
2 Change the directory to the project folder using:
cd <project name>
3 Open Visual Studio code using:
code .
4 Create separate containers using:
nx generate @nrwl/angular:app <container name>
5 Compile and run all containers using:
nx run <container name>:serve:development - port <port>
Note: You can also use ng instead of nx
6 Use the following command to create new components:
nx generate @nrwl/angular:component <component name> - project <project name>
7 Set up module federation in all containers:
npm i @angular-architects/module-federation
8 Run the following command to add webconfig file to all the containers:
ng g @angular-architects/module-federation:init
• Select container and assign port
9 Expose the component you want to use in other containers in webpack.config.js:
exposes: {
'./Module': './apps/<container-name>/src/app/remote-entry/remote-entry.module.ts',
},
10 Use the exposed module in the routing of app.module.ts of the shell container:
RouterModule.forRoot(
[
{
path: '<container-name>',
loadChildren: () =>
loadRemoteModule({
remoteEntry: 'http://localhost:<port>/remoteEntry.js',
type: 'module',
exposedModule: './Module',
}).then((m) => m.RemoteEntryModule),
}
],
{ initialNavigation: 'enabledBlocking' }
)
],
11 In order to create a shared service in a shared folder, use:
ng g @nrwl/angular:lib shared/test-service
12 Install ngx-mfe (version 3.0.2):
npm i ngx-mfe
13 Create index.ts file and import:
export * from './lib/shared-test-service.module';
export * from './lib/test-service.service';
14 Add the path to tsconfig.base.json:
"paths": {
"@micro-frontends/shared/test-service": ["libs/shared/test-service/src/index.ts"]
}
15 Add the shared service to the webpack.config.js file of the container you want to use the service in:
sharedMappings.register(sharedMappings.register(
path.join(__dirname, '../../tsconfig.base.json'),
path.join(__dirname,'../../tsconfig.base.json'),
[/* mapped paths to share */]);
['@micro-frontends/shared/shared/test-service']);]);
16 In order to use the service, import it into the component:
import{{ TestService }} from '@micro-frontends/shared/test-service'
Note: Please change micro-frontends to the name of your project and test-service to the name of your service in the above commands.
Happy Coding!
Posted on March 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 10, 2023