How to host assets with Module Federation on Angular and Nx monorepo
14:35 05 Mar 2022

I need to make assets (png, svg images, fonts) from Angular remote applications available also in host applications of Webpack Module Federation.

Below are long steps to reproduce - not necessary to read if you know the solution :)


Preconditions:

  • Nx monorepo workspace. - Created by following these steps: https://nx.dev/guides/setup-mfe-with-angular
  • libs/shared/assets - a shared library with just two images. This is optional, the solution can be without this shared lib (put assets directly to login).
  • apps/login - a remote app that uses assets library
  • apps/dashboard - a host app, that uses login app
  • from dashboard and login apps I have symbolic links to assets - this can be removed too.
  • the actual code is hosted here: https://github.com/Kichrum/module-federation-demo (so-question branch, clone with symlinks: git clone -c core.symlinks=true https://github.com/Kichrum/module-federation-demo.git).
  • to run: npm i && npm start

Expected result:

on http://localhost:4200 (host) and http://localhost:4201/ (remote) we have 4 images visible. When building the apps (npm run build), both apps have assets (can be hosted on CDN).

login app host app

I've tried to play with package.json, webpack.config.json - didn't help (maybe did sth wrong).

For now, I have a solution: host all the assets somewhere on separate CDNs, write absolute URLs in the source code, but then I have to keep CDN and code in sync - doesn't look like a long-term solution.

UPD: Avoiding relative path usage in CSS "fixes" the problem: url('^assets/img.png') or url('/assets/img.png'). Dev and prod build work good, but the solution isn't perfect, because:

  1. IDE underlines such paths as invalid (can't find /assets in project root) - moving /assets folder to the same level as apps/ fixes it;
  2. Filenames are not extended with hashcode for better caching;
  3. Nx and Angular 13 CLI caching mechanism sometimes "forgets" to update assets, so on build w/o flag --skip-nx-cache I miss new assets.

All three points are manageable, but they are "symptoms" of tech debt, so I hope community has better solution, at least without symlinks.

angular assets monorepo webpack-module-federation nomachine-nx