1027 words
5 minutes
Embedding the Logitech Project as a Subsystem

Why Convert It into a Subsystem#

The current Logitech project is built on Angular, and it is riddled with bugs. On top of that, a phase-two build is on the roadmap, and nobody on the frontend team is particularly comfortable with Angular. Given all of this, the most sensible plan was to rework the project into a subsystem, so phase two can be built as a separate subsystem in React — a framework the whole team knows well.

Choosing a Micro-Frontend Framework#

icestark is a micro-frontend solution aimed at large systems. It fits these scenarios:

  • Admin consoles scattered across many apps with inconsistent UX, where constant context-switching drags down efficiency, and you want everything consolidated under one roof
  • A single-page app so huge that multi-team collaboration is costly, builds take forever, and every dependency upgrade means an expensive regression cycle
  • The system needs to host second-party or third party integrations

While preserving the experience of a single unified system, icestark lets each micro-app develop and ship independently. The host app manages registration and rendering of the micro-apps through icestark, decoupling the system completely.

Overall Design#

Logitech project embedding design

Host App Design#

We took the Logitech project that was refactored in mid-2023 and turned it into the host app, which owns login, permissions, layout, menus, and other global concerns.

Tech stack

Integration

  1. Install @ice/stark
Terminal window
npm i --save @ice/stark
  1. Register the micro-app
import { AppRouter, AppRoute } from '@ice/stark';
function Layout() {
return (
<div className="Layout">
<AppRouter>
<AppRoute
activePath="/logitech"
title="罗技angular一期"
entry="http://127.0.0.1:4200"
/>
<div style={{ padding: 20 }}>
<Outlet />
</div>
</AppRouter>
</div>
)
}
export default Layout;

Micro-App Design (the Phase-One Angular Project)#

We used icestark to convert the Logitech project into a subsystem.

Integration

Follow the official Angular integration guide.

The Problems

Once you wire it up per the guide and add the corresponding menu entries to the host app, two issues surface:

  1. Static assets — images, fonts, icons — fail to load
  2. Navigating between pages via the menu doesn’t work

Fixing the Broken Static Assets

The browser console’s network tab shows why: the asset URLs are wrong. They are being requested relative to the host app’s origin.

Static assets requested against the wrong base path

What I tried first:

  1. Setting webpack’s publicPath (didn’t help)
  2. Setting the href of the base tag in index.html (didn’t help)

What actually works:

  1. Upload all static assets to OSS object storage and update the references (works, but the project has a mountain of assets and re-pointing every one is a slog)
  2. Rewrite asset URLs in the project as absolute paths

I went with option 2. Concretely:

  • For assets referenced in templates, rewrite them through a custom Angular pipe
  • For assets referenced in components, rewrite them through a custom global function
  • For assets referenced in stylesheets, splice the prefix in with an scss variable
  • For icons from the Ant Design of Angular component library, importing them globally makes them render correctly

Templates

  1. Create the pipe

Create a pipe folder under src->app with an asset-url.pipe.ts file inside:

import { Pipe, PipeTransform } from '@angular/core';
import { assetUrl } from '@app/utils'
@Pipe({
name: 'assetUrl'
})
export class AssetUrlPipe implements PipeTransform {
transform(value: string, ...args: unknown[]): unknown {
return assetUrl(value);
}
}

The imported assetUrl function is introduced below, in the section on fixing component assets.

  1. Create a SharedModule

Create a shared folder under src->app with a shared.module.ts file inside:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AssetUrlPipe } from '../pipe/asset-url.pipe'; // update to the actual path of the assetUrl pipe
@NgModule({
declarations: [AssetUrlPipe],
imports: [
CommonModule
],
exports: [AssetUrlPipe] // don't forget to export it
})
export class SharedModule { }
  1. Use the pipe in templates

In the module of whichever page needs the pipe, import SharedModule:

import { SharedModule } from "@app/shared/shared.module";

Then use it in the template:

<img [src]="'/assets/images/1520.png' | assetUrl" alt="">

Components

  1. Create the global function

Create a utils folder under src->app with an index.ts file inside:

export function assetUrl(url: string): string {
// @ts-ignore
const publicPath = __webpack_public_path__;
const publicPathSuffix = publicPath.endsWith('/') ? '' : '/';
const urlPrefix = url.startsWith('/') ? '' : '/';
return `${publicPath}${publicPathSuffix}${urlPrefix}${url}`;
}
  1. Use the global function

In the component that needs it, import assetUrl:

import { assetUrl } from '@app/utils';

Then apply it:

const list = [
{
icon: assetUrl('assets/images/salesYoy.png'),
},
];

Stylesheets

Declare the base URL in the stylesheet and interpolate it:

$assets-dev: 'http://127.0.0.1:4200/assets';
.toFullScreen{
background:url(#{$assets-content-dev}/images/fullscreen.jpeg);
}

Icons

import * as AllIcons from '@ant-design/icons-angular/icons';
const antDesignIcons = AllIcons as {
[key: string]: IconDefinition;
};
const icons: IconDefinition[] = Object.keys(antDesignIcons).map(key => antDesignIcons[key])
@NgModule({
declarations: [
AppComponent
],
imports: [
NzIconModule.forRoot(icons)
]
bootstrap: [ AppComponent ]
})
export class AppModule {
}

Result#

All images now load.

Logitech project embedded, assets loading

Fixing Menu Navigation

The route navigation fails for reasons I never fully pinned down. While debugging, I noticed the first navigation gets interrupted with a NavigationCancel event and the page stays where it is, with this error:

{
"id": 3,
"url": "/businessOverview",
"reason": "Navigation ID 3 is not equal to the current navigation id 4"
}

The full sequence of events Angular’s router fires during a navigation:

  1. NavigationStart: fired when navigation starts.
  2. RouteConfigLoadStart: fired when the Router lazy-loads an async route configuration.
  3. RouteConfigLoadEnd: fired when the route configuration finishes loading.
  4. RoutesRecognized: fired when the Router has parsed the URL and matched it against route configurations.
  5. GuardsCheckStart: fired when the Router starts running CanActivate and CanDeactivate guards.
  6. ChildActivationStart: fired when the Router begins activating a route’s child routes.
  7. ActivationStart: fired when the Router begins activating a route.
  8. GuardsCheckEnd: fired when the Router finishes running the guards.
  9. ResolveStart: fired when the Router starts resolving the route.
  10. ResolveEnd: fired when route resolution completes.
  11. ChildActivationEnd: fired when the Router finishes activating a route’s child routes.
  12. ActivationEnd: fired when the Router finishes activating a route.
  13. NavigationEnd: fired when navigation ends successfully.
  14. NavigationCancel: fired when navigation is cancelled (possibly because a guard returned false).
  15. NavigationError: fired when navigation fails.

Interestingly, if you navigate to the same route a second time, it goes through just fine. That suggests a workaround: on navigation, wait a beat with setTimeout and navigate again. The route lands correctly this time, but the page doesn’t render properly — the previous page’s content is still on screen with the new page rendered below it, or sometimes not rendered at all. Forcing a page reload fixes that, at some cost to user experience.

navigate(`/${menuInfo.key}`);
// If the path starts with /logitech/, load the logitech micro-app
if (menuInfo.key.startsWith('logitech/')) {
setTimeout(() => {
navigate(`/${menuInfo.key}`);
window.location.reload();
}, 50);
}

Micro-App Design (the Phase-Two React Project)#

Just scaffold a fresh React project.

Final Result#

Logitech project embedded, final result

Logitech project embedding, final view

Embedding the Logitech Project as a Subsystem
https://www.mihouo.com/en/posts/front/implementing-logitech-projects-as-embedded-subsystems/
Author
Jia
Published at
2024-01-12
License
CC BY-NC-SA 4.0