angular-architects / module-federation-plugin

MIT License
737 stars 203 forks source link

Host receive dependecy from Child MFE #141

Open Eduk29 opened 2 years ago

Eduk29 commented 2 years ago

Hi

I have two microfrontends applications (Host and Product) in angular v.13 and using the concept of module federation with webpack 5. My Product application uses the Angular Material library and when I'm running the Product application and accessing it through local url, the button (with angular material styles) renders correctly. However, when I access through my Host application, the button lose the styles coming from angular material. I wouldn't want to have to add Angular Material as a dependency of my Host application. Is there any way for the Product application to export angular material styles and settings?

Tks

cyrixmorten commented 2 years ago

Hi @Eduk29

The way we did this was to:

  1. create a shared library containing all of our styling (including setup of material)
  2. create another library that exposes Angular Material modules (something in the lines of https://fireflysemantics.medium.com/creating-a-shared-angular-material-module-73dfb32f0838) - simply create an angular library and re-export the material modules that your application needs.

Shared styling

Update the project.json both apps:

"targets": {
  "build": {
      ...
       "assets": [
          "apps/<app-name>/app/src/favicon.ico",
          "apps/<app-name>/app/src/assets",
          { // this snippet is not directly related to your question but a nice way to share assets 
            "glob": "**/*.{png,json,jpg}",
            "input": "libs/shared/resources/src/lib", 
            "output": "./assets"
          }
        ],
        "styles": ["apps/<app-name>/app/src/styles.scss"],
        "stylePreprocessorOptions": {
          "includePaths": ["libs/shared/theme/src/lib/scss"]
        },
  }
}

Finally, in apps/<app-name>/app/src/styles.scss import your theme (we are using scss)

@import 'theme';

This assumes that the styles are exposed as a barrel scss that includes alll the relevant styles. In our theme library we have libs/shared/theme/src/lib/scss/theme.scss containing:

@import './normalize.scss';
@import './init-basics.scss';
@import './colors.scss';
@import './material.scss';
@import './fonts.scss';
@import './tailwind.scss';

Since we added the whole folder as stylePreprocessorOptions in project.json, adding @import 'theme' will pick up the theme.scss file at libs/shared/theme/src/lib/scss/theme.scss.

This pattern can be repeated for all MFE apps to share stylings (including material stylings). Re-using the styles from a common library.

Shared Angular Material Module

The shared Angular Material module from step 2 should simply be imported at the parts of your application that needs material components.


Hope I managed to explain how this could be accomplished