Skip to content

๐Ÿš€๐ŸŒ๐Ÿš€A powerful, reliable, fully-featured and production ready Micro Frontend library for Angular.

License

Notifications You must be signed in to change notification settings

worktile/ngx-planet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

ngx-planet

CircleCI Coverage Status npm (scoped) npm npm bundle size (scoped) All Contributors

A powerful, reliable, fully-featured and production ready Micro Frontend library for Angular.

APIs consistent with angular style, currently only supports Angular, other frameworks are not supported.

English | ไธญๆ–‡ๆ–‡ๆกฃ

โœจ Features

  • Rendering multiple applications at the same time
  • Support two mode, coexist and default that switch to another app and destroy active apps
  • Support application preload
  • Support style isolation
  • Built-in communication between multiple applications
  • Cross application component rendering
  • Comprehensive examples include routing configuration, lazy loading and all features

๐Ÿ“– Documentation

Alternatives

  • single-spa: A javascript front-end framework supports any frameworks.
  • mooa: A independent-deployment micro-frontend Framework for Angular from single-spa, planet is very similar to it, but planet is more powerful, reliable, productively and more angular.

Installation

$ npm i @worktile/planet --save
// or
$ yarn add @worktile/planet

Demo

Try out our live demo

ngx-planet-micro-front-end.gif

Usage

1. Loading NgxPlanetModule in the portal's AppModule

import { NgxPlanetModule } from '@worktile/planet';

@NgModule({
  imports: [
    CommonModule,
    NgxPlanetModule
  ]
})
class AppModule {}

2. Register applications to planet use PlanetService in portal app

@Component({
    selector: 'app-portal-root',
    template: `
        <nav>
            <a [routerLink]="['/app1']" routerLinkActive="active">ๅบ”็”จ1</a>
            <a [routerLink]="['/app2']" routerLinkActive="active">ๅบ”็”จ2</a>
        </nav>
        <router-outlet></router-outlet>
        <div id="app-host-container"></div>
        <div *ngIf="!loadingDone">ๅŠ ่ฝฝไธญ...</div>
    `
})
export class AppComponent implements OnInit {
    title = 'ngx-planet';

    get loadingDone() {
        return this.planet.loadingDone;
    }

    constructor(
        private planet: Planet
    ) {}

    ngOnInit() {
        this.planet.setOptions({
            switchMode: SwitchModes.coexist,
            errorHandler: error => {
                console.error(`Failed to load resource, error:`, error);
            }
        });

        this.planet.registerApps([
            {
                name: 'app1',
                hostParent: '#app-host-container',
                hostClass: 'thy-layout',
                routerPathPrefix: '/app1',
                preload: true,
                entry: "/static/app2/index.html"
            },
            {
                name: 'app2',
                hostParent: '#app-host-container',
                hostClass: 'thy-layout',
                routerPathPrefix: '/app2',
                preload: true,
                entry: {
                  basePath: "/static/app1/"
                  manifest: "index.html"
                  scripts: [
                    'main.js'
                  ],
                  styles: [
                    'styles.css'
                  ]
                }
            }
        ]);

        // start monitor route changes
        // get apps to active by current path
        // load static resources which contains javascript and css
        // bootstrap angular sub app module and show it
        this.planet.start();
    }
}

3. Sub App define how to bootstrap

for NgModule application:

defineApplication('app1', {
    template: `<app1-root class="app1-root"></app1-root>`,
    bootstrap: (portalApp: PlanetPortalApplication) => {
        return platformBrowserDynamic([
            {
                provide: PlanetPortalApplication,
                useValue: portalApp
            },
            {
                provide: AppRootContext,
                useValue: portalApp.data.appRootContext
            }
        ])
            .bootstrapModule(AppModule)
            .then(appModule => {
                return appModule;
            })
            .catch(error => {
                console.error(error);
                return null;
            });
    }
});

for Standalone application: (>= 17.0.0)

defineApplication('standalone-app', {
    template: `<standalone-app-root></standalone-app-root>`,
    bootstrap: (portalApp: PlanetPortalApplication) => {
        return bootstrapApplication(AppRootComponent, {
            providers: [
                {
                    provide: PlanetPortalApplication,
                    useValue: portalApp
                },
                {
                    provide: AppRootContext,
                    useValue: portalApp.data.appRootContext
                }
            ]
        }).catch(error => {
            console.error(error);
            return null;
        });
    }
});

Documents

Sub app configurations

Name Type Description ไธญๆ–‡ๆ่ฟฐ
name string Application's name ๅญๅบ”็”จ็š„ๅๅญ—
routerPathPrefix string Application route path prefix ๅญๅบ”็”จ่ทฏ็”ฑ่ทฏๅพ„ๅ‰็ผ€๏ผŒๆ นๆฎ่ฟ™ไธชๅŒน้…ๅบ”็”จ
selector string selector of app root component ๅญๅบ”็”จ็š„ๅฏๅŠจ็ป„ไปถ้€‰ๆ‹ฉๅ™จ๏ผŒๅ› ไธบๅญๅบ”็”จๆ˜ฏไธปๅบ”็”จๅŠจๆ€ๅŠ ่ฝฝ็š„๏ผŒๆ‰€ไปฅไธปๅบ”็”จ้œ€่ฆๅ…ˆๅˆ›ๅปบ่ฟ™ไธช้€‰ๆ‹ฉๅ™จ่Š‚็‚น๏ผŒๅ†ๅฏๅŠจ AppModule
entry string | PlanetApplicationEntry entry for micro app, contains manifest, scripts, styles ๅ…ฅๅฃ้…็ฝฎ๏ผŒๅฆ‚ๆžœๆ˜ฏๅญ—็ฌฆไธฒ่กจ็คบๅบ”็”จๅ…ฅๅฃ index.html๏ผŒๅฆ‚ๆžœๆ˜ฏๅฏน่ฑก, manifest ไธบๅ…ฅๅฃ html ๆˆ–่€… json ๆ–‡ไปถๅœฐๅ€๏ผŒscripts ๅ’Œ styles ไธบๆŒ‡ๅฎš็š„่ต„ๆบๅˆ—่กจ๏ผŒๆœชๆŒ‡ๅฎšไฝฟ็”จ manifest ๆŽฅๅฃไธญ่ฟ”ๅ›ž็š„ๆ‰€ๆœ‰่ต„ๆบ๏ผŒbasePath ไธบๅŸบๆœฌ่ทฏ็”ฑ๏ผŒๆ‰€ๆœ‰็š„่ต„ๆบ่ฏทๆฑ‚ๅœฐๅ€ๅ‰ไผšๅธฆไธŠ basePath
manifest string manifest json file path deprecated please use entry manifest.json ๆ–‡ไปถ่ทฏๅพ„ๅœฐๅ€๏ผŒๅฝ“่ฎพ็ฝฎไบ†่ทฏๅพ„ๅŽไผšๅ…ˆๅŠ ่ฝฝ่ฟ™ไธชๆ–‡ไปถ๏ผŒ็„ถๅŽๆ นๆฎ scripts ๅ’Œ styles ๆ–‡ไปถๅๅŽปๆ‰พๅˆฐๅŒน้…็š„ๆ–‡ไปถ๏ผŒๅ› ไธบ็”Ÿไบง็Žฏๅขƒ็š„้™ๆ€่ต„ๆ–‡ไปถๆ˜ฏ hash ไน‹ๅŽ็š„ๅ‘ฝๅ๏ผŒ้œ€่ฆๅŠจๆ€่Žทๅ–
scripts string[] javascript static resource paths deprecated please use entry.scripts JS ้™ๆ€่ต„ๆบๆ–‡ไปถ่ฎฟ้—ฎๅœฐๅ€
styles string[] style static resource paths deprecated please use entry.styles ๆ ทๅผ้™ๆ€่ต„ๆบๆ–‡ไปถ่ฎฟ้—ฎๅœฐๅ€
resourcePathPrefix string path prefix of scripts and styles deprecated please use entry.basePath ่„šๆœฌๅ’Œๆ ทๅผๆ–‡ไปถ่ทฏๅพ„ๅ‰็ผ€๏ผŒๅคšไธช่„šๆœฌๅฏไปฅ้ฟๅ…้‡ๅคๅ†™ๅŒๆ ท็š„ๅ‰็ผ€
hostParent string or HTMLElement parent element for render ๅบ”็”จๆธฒๆŸ“็š„ๅฎนๅ™จๅ…ƒ็ด , ๆŒ‡ๅฎšๅญๅบ”็”จๆ˜พ็คบๅœจๅ“ชไธชๅ…ƒ็ด ๅ†…้ƒจ
hostClass string added class for host which is selector ๅฎฟไธปๅ…ƒ็ด ็š„ Class๏ผŒไนŸๅฐฑๆ˜ฏๅœจๅญๅบ”็”จๅฏๅŠจ็ป„ไปถไธŠ่ฟฝๅŠ ็š„ๆ ทๅผ
switchMode default or coexist it will be destroyed when set to default, it only hide app when set to coexist ๅˆ‡ๆขๅญๅบ”็”จ็š„ๆจกๅผ๏ผŒ้ป˜่ฎคๅˆ‡ๆขไผš้”€ๆฏ๏ผŒ่ฎพ็ฝฎ coexist ๅŽๅชไผš้š่—
preload boolean start preload or not ๆ˜ฏๅฆๅฏ็”จ้ข„ๅŠ ่ฝฝ๏ผŒๅฏๅŠจๅŽๅˆทๆ–ฐ้กต้ข็ญ‰ๅฝ“ๅ‰้กต้ข็š„ๅบ”็”จๆธฒๆŸ“ๅฎŒๆฏ•ๅŽ้ข„ๅŠ ่ฝฝๅญๅบ”็”จ
loadSerial boolean serial load scripts ๆ˜ฏๅฆไธฒ่กŒๅŠ ่ฝฝ่„šๆœฌ้™ๆ€่ต„ๆบ

Communication between applications use GlobalEventDispatcher

import { GlobalEventDispatcher } from "@worktile/planet";

// app1 root module
export class AppModule {
    constructor(private globalEventDispatcher: GlobalEventDispatcher) {
        this.globalEventDispatcher.register('open-a-detail').subscribe(event => {
            // dialog.open(App1DetailComponent);
        });
    }
}

// in other apps
export class OneComponent {
    constructor(private globalEventDispatcher: GlobalEventDispatcher) {
    }

    openDetail() {
        this.globalEventDispatcher.dispatch('open-a-detail', payload);
    }
}

Cross application component rendering

import { PlanetComponentLoader } from "@worktile/planet";

// in app1
export class AppModule {
    constructor(private planetComponentLoader: PlanetComponentLoader) {
        this.planetComponentLoader.register([App1ProjectListComponent]);
    }
}

Load app1-project-list (selector) component of app1 in other app via PlanetComponentOutlet

<ng-container *planetComponentOutlet="'app1-project-list'; app: 'app1'; initialState: { search: 'xxx' }"></ng-container>

// or 
<ng-container planetComponentOutlet="app1-project-list"
              planetComponentOutletApp="app1"
              [planetComponentOutletInitialState]="{ term: 'xxx' }"
              (planetComponentLoaded)="planetComponentLoaded($event)">
</ng-container>

Load app1-project-list component of app1 in other app via PlanetComponentLoader, must be call dispose

@Component({
  ...
})
export class OneComponent {
    private componentRef: PlanetComponentRef;

    constructor(private planetComponentLoader: PlanetComponentLoader) {
    }

    openDetail() {
        this.planetComponentLoader.load('app1', 'app1-project-list', {
            container: this.containerElementRef,
            initialState: {}
        }).subscribe((componentRef) => { 
            this.componentRef = componentRef;
        });
    }

    ngOnDestroy() {
       this.componentRef?.dispose();
    }
}

FAQ

infinite loop load portal app's js

Because the portal app and sub app are packaged through webpack, there will be conflicts in module dependent files, we should set up additional config runtimeChunk through @angular-builders/custom-webpack, we expect webpack 5 to support micro frontend better.

// extra-webpack.config.js
{    
    optimization: {
        runtimeChunk: false
    }
};

throw error Cannot read property 'call' of undefined at __webpack_require__ (bootstrap:79)

Similar to the reasons above, we should set vendorChunk as false for build and serve in angular.json

 ...
 "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
          "customWebpackConfig": {
              "path": "./examples/app2/extra-webpack.config.js",
              "mergeStrategies": {
                "module.rules": "prepend"
              },
              "replaceDuplicatePlugins": true
          },
          ...
          "vendorChunk": false,
          ...
      },
  },
  "serve": {
      "builder": "@angular-builders/custom-webpack:dev-server",
      "options": {
          ...
          "vendorChunk": false
          ...
      }
  }
...

throw error An accessor cannot be declared in an ambient context.

this is TypeScript's issue, details see an-accessor-cannot-be-declared should setting skipLibCheck as true

"compilerOptions": {
    "skipLibCheck": true
}

Production env throw error Cannot read property 'call' of undefined use router lazy load

In webpack 4 multiple webpack runtimes could conflict on the same HTML page, because they use the same global variable for chunk loading. To fix that it was needed to provide a custom name to the output.jsonpFunction configuration, details see Automatic unique naming.

you should set a unique name for each sub application in extra-webpack.config.js

output: { jsonpFunction: "app1" }

Development

npm run start // open http://localhost:3000

or

npm run serve:portal // 3000
npm run serve:app1 // 3001
npm run serve:app2 // 3002

// test
npm run test

Roadmap

  • Ivy render engine
  • Supports Other frameworks as React and Vue

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


why520crazy

๐Ÿ’ฌ ๐Ÿ’ผ ๐Ÿ’ป ๐ŸŽจ ๐Ÿ“– ๐Ÿ“‹ ๐Ÿš‡ ๐Ÿšง ๐Ÿ“† ๐Ÿ‘€

Walker

๐Ÿ’ป ๐Ÿ’ก ๐Ÿšง ๐Ÿ‘€

whyour

๐Ÿ’ป

ๅผ ๅจ

๐Ÿ’ป

luxiaobei

๐Ÿš‡ โš ๏ธ ๐Ÿ’ป

mario_ma

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT License