Search code examples
reactjsmaterial-uicustom-element

How to share libraries across web components


I've started a micro frontends project by utilizing custom elements. I'm looking for a way to share dependencies between all of the parts of the application.

I'm wondering how I could do this with Material-ui library. For example one could attach library to the window object and access it from inside of the custom element (web component).

The problem that I'm seeing here is that the material-ui exists as a npm module, and I haven't managed to find an option to load it via script tag.

The custom elements are loaded via http import enter image description here which means that they will be loaded before the window object has been populated with the material-ui library.


Solution

  • I found one way of sharing libraries, for example UI libraries, such as Material-UI, and that is by putting them on a global scope (window object).

    Then the web component (custom element) which is being included in the composition layer can read it from the window object inherited from the context in which it's included.

    This approach can be easily used in case when there is only functionality needed. In case of UI library, where there is style as well, one has to pay attention if the shadow dom is turned on or not on the web component, and turn it off if it is.

    Reason for this is the web component's shadow dom styles scoping capability, meaning one can simply inherit styles from a parent.

    Here's a quick sample that I've made last year and now I've just made it work again :) github.com/mnemanja/web-components-composition