Search code examples
angularsingle-spa

Choose where to render application on root HTML with Single-SPA


I'm planning to use single-SPA framework with angular to build a microfrontend architecture to a website. The website already exists in a legacy monolith way and we are planning to strangle it to microfrontend architecture to have independent teams working and doing independent deploys.

My plan is to use the actual monolith as the root for single-SPA and strangle the microfrontends one by one, coexisting with the actual monolith. I did some tests and the coexistence is possible but single-SPA always render the applications at the end of my page.

The question is if it's possible to render the application with single-SPA into a specific location on my HTML as inside a specific div element, for example. It's a really simple test i've been doing by now and this is how I'm registering the angular applications on single-SPA. By doing this it always render the application at the end of my body element.

         <script>
            System.import('single-spa').then(function (singleSpa) {

                singleSpa.registerApplication(
                    'dashboard',
                    function () {
                        return System.import('dashboard');
                    },
                    function (location) {
                        return location.pathname.startsWith('/dashboard');
                    }
                );

                singleSpa.start();
            })
        </script>

Solution

  • The answer to this isn't as straighforward so I'll break it up.

    My plan is to use the actual monolith as the root for single-SPA and strangle the microfrontends one by one, coexisting with the actual monolith.

    The single-spa team recommends not trying to put the root config into an application for better separation of concerns. See also "Should I have a parent/root app and children apps" and "Architectural overview". Instead, you should have an independent root-config and your first single-spa application should be the monolith.

    The question is if it's possible to render the application with single-SPA into a specific location on my HTML

    This is possible at the single-spa application level by passing in a domElementGetter option to singleSpaAngular.

    Alternatively, you can achieve the same thing from the config if using single-spa-layout in the root config.

    as inside a specific div element

    This is where I felt there was some need to further delve in. While you can have the application mounted at an arbitrary place in the DOM, you should not expect to try to mount a single-spa application within a single-spa application. Instead components can be shared through cross microfrontend imports if using the same framework between them, or single-spa Parcels for cross-framework interop.