• Stars
    star
    570
  • Rank 78,245 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Make Web Components easier and powerful!😘

Magic Microservices

Micro frontends made easy.

Build Status codecov npm GitHub

English | 简体中文

Overview

A lightweight micro-frontends function factory based on Web Components.

Features

  • Small: small bundle size (ESM Browser: 2.4KB;ESM/CJS:3.7KB;UMD:3.7KB)
  • 🚀 Portability: write your code and use it with any frameworks.
  • 🔨 Adaptable: an adapter for any JS module, friendly to existing code.
  • 💪 Web Components +: empower native Web Components

Quick Start

  1. Download and include the magic functions with a script tag.
<html>
  <body>
    <script src="https://unpkg.com/@magic-microservices/magic@latest/dist/index.umd.js"></script>
  </body>
</html>
  1. Register your first micro-frontends application.
<html>
  <body>
    <script src="https://unpkg.com/@magic-microservices/magic@latest/dist/index.umd.js"></script>
    <script>
      magic('custom-component', {
        mount: (container) => (container.innerHTML = 'Hello magic!'),
      });
    </script>
  </body>
</html>
  1. Use your registered micro-frontends application with an HTML tag.
<html>
  <body>
    <custom-component></custom-component>
    <script src="https://unpkg.com/@magic-microservices/magic@latest/dist/index.umd.js"></script>
    <script>
      magic('custom-component', {
        mount: (container) => (container.innerHTML = 'Hello magic!'),
      });
    </script>
  </body>
</html>

Install

Compatibility Note

Magic Microservices is built upon Web Components. The compatibility of Magic is thus equivalent to that of Web Components.

Core Logic Compatibility

from caniuse.com

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
IE11, Edge last 2 versions last 2 versions last 2 versions last 2 versions

If you need to support IE11 or pre-Chromium Edge, this library isn't for you. Although Web Components can (to some degree) be polyfilled for legacy browsers, supporting them is outside the scope of this project. If you're using Magic in such a browser, you're gonna have a bad time.

Directly <script> Include

UMD

We have built a UMD package which can be included directly into your HTML:

<script src="https://unpkg.com/@magic-microservices/magic@latest/dist/index.umd.js"></script>

The window object has window.magic and window.magic.useProps functions, which can be used with the externals mechanism.

We also provide compressed packages. If you are in production mode, please replace index.umd.js with index.umd.min.js, which is optimized for speed instead of the development experience.

ES Module

For modern browsers, you can also use the ES Module approach to introduce the core logic:

<script type="module">
  import magic, { useProps } from 'https://unpkg.com/@magic-microservices/magic@latest/dist/index.esm.browser.js';
</script>

We can use our methods directly. PS: ES Module Compatibility: https://caniuse.com/es6-module

NPM

If you want Magic to follow your project with module bundlers like webpack, you can also install our NPM package:

# the latest version
$ npm i @magic-microservices/magic

and use our functions as below:

import magic, { useProps } from '@magic-microservices/magic';

Develop your microfrontends application

Transform

Transform your JS module into a "Magic"

The difference between a Magic module and a normal JS Module is that you need to export specific functions to make the required response to the module's rendering, update or unmount steps in the Magic module, and these functions need to conform to the definition of Magic lifecycle.

Module lifecycle

Each module will go through a series of mount, update and unmount, similar to every HTML element. You can define what happens at each life stage of your module.

LifeCycle Interface

You can define those lifecycle functions as indicated below in your JS module. These functions will be triggered at different application stages.

type ValueOf<T> = T[keyof T];

interface Module<Props extends Record<string, unknown>> {
  bootstrap?: () => void;
  firstUpdated?: (attributeName: keyof Props, propsValue: ValueOf<Props>, container: Element, props: Props) => void;
  mount: (container: Element, props: Props) => void;
  updated?: (attributeName: keyof Props, propsValue: ValueOf<Props>, container: Element, props: Props) => void;
  unmount?: () => void;
}
Lifecycle details
Bootstrap

You can execute some logic which is required by micro application before DOM mounted, such as pulling and initializing i18n resource.

FirstUpdated

Called will be triggered when initializing every single prop field from DOM attributes before micro-application mount to the DOM. References can be found on Web Components' attributeChangedCallback API.

Mount

This function is used to mount your application. Similar to react-dom's render function, this function takes a container element and the props you want to pass to your app, and renders your application into the container. If you are familiar with Web Components, you may find this function do the same thing as the connectedCallback API.

Updated

The updated function will be called every time a DOM attribute has changed. You can use it to manage the derived data. It does the same job as Web Components' attributeChangedCallback API.

Unmount

The unmount function is called when the application is about to be unmounted or destroyed. It is primarily used for cleanups, such as cancelling timers, dropping network requests, and unsubscribing event listeners.

Lifecycle diagram

Below is a diagram for the instance lifecycle. You don’t need to fully understand everything going on right now, but as you learn and build more, it will be a useful reference.

lifecycle diagram

Code Example

You can refer to the two code snippets using React and Vue (3) below to implement your own JS module.

React:
import React from 'react';
import ReactDOM from 'react-dom';
import List from './component/List.jsx';

const dataList = [{ name: 'hello' }, { name: 'world' }, { name: 'react' }, { name: 'react-dom' }];

export async function bootstrap() {
  console.log('magic-microservices-component bootstraped');
}

export async function mount(container, props) {
  console.log('magic-microservices-component mount >>> ', props);
  ReactDOM.render(React.createElement(List, { ...props, dataList }, null), container);
}

export async function updated(attrName, value, container, props) {
  console.log('magic-microservices-component update >>> ', props);
  ReactDOM.render(React.createElement(List, { ...props, dataList }, null), container);
}

export async function unmount() {
  console.log('magic-microservices-component will unmount');
}
Vue (3):
import Vue from 'vue/index';
import App from './component/Hello.vue';

let vueInstance = null;

export async function bootstrap() {
  console.log('vue app bootstraped');
}

export async function mount(container, props) {
  console.log('magic-microservices-component-vue mount >>> ', props);
  vueInstance = Vue.createApp({
    ...App,
    data() {
      return props;
    },
  }).mount(container);
}

export async function updated(attrName, value) {
  console.log('magic-microservices-component-vue update', attrName, ' >>> ', value);
  vueInstance[attrName] = value;
  vueInstance.$forceUpdate();
}

export async function unmount() {
  console.log('vue app will unmount');
}

Register

Register: Register your Magic modules as a "microfrontends applications" which HTML natively supported.

Get your Magic module

Local package

You can import your Magic module (published packages or local module) and pass it as the second argument into magic function:

import magic from '@magic-microservices/magic';
import MyModule from '/path/to/your/module';

magic('custom-component', MyModule);
Remote Package (UMD)

You can get your Magic module directly if it's already been deployed remotely via UMD. Include your remote UMD module through HTML script tag like:

<script src="https://somewhere/to/your/module/index.umd.js"></script>

If your Magic module is already registered on the window, you can use it directly via global variables:

magic('custom-component', window.MyModule);
Remote Package (ES Module)

Of course, similar to UMD, you can also use the ES Module remote package directly like:

<script type="module">
  import MyModule from 'https://somewhere/to/your/module/index.esm.js';
  magic('custom-component', MyModule);
</script>
SystemJS

If you are using a package registered with SystemJS, then everything becomes easier:

magic('custom-component', System.import('https://somewhere/to/your/module/index.system.js'));

PS: Advantages of System JS:

  • It can load both remote packages and local packages
  • It does not require npm install compared to CJS
  • It does not need to focus on global variables on windows compared to UMD
  • It doesn't need to care about compatibility issues compared to ESM

Your Magic module can now finally be built into a module of any mode, such as NPM package, ES Module package, UMD package or SystemJS package, etc., as long as it can be fetched from the remote at the time of registration.

We recommend using SystemJS as your first choice for modularity, because this solution is more friendly to the package-include experience and compatibility of remote-package components.

Props

You need to specify the types of all the props for your micro-application in the propTypes attribute as highlighted below. Otherwise, you won't be able to pass down the props, which also means your Web Components' event listeners won't be triggered at all (WebComponents specification constraints). This is an example:

magic('my-component', window.MyModule, {
  propTypes: {
    id: Number,
    test: Boolean,
    callback: Function,
    count: Number,
  },
});

The definition of the type PropTypesMap for propTypes is as follows:

type PropTypes = typeof Number | typeof Boolean | typeof String | typeof Array | typeof Function | typeof Object;

interface PropTypesMap {
  [propsName: string]: PropTypes;
}
  • propsName: name of props
  • PropsTy[es: the type of props (using the JS native type constructor, for example: Number)
Special handling of reference type data in props

We all have known that WebComponents is an HTML specification, so our generated Custom Component (Custom Element) can only support character string to pass attributes.

Magic enables WebComponents to pass reference type attributes by using useProps method. If you want to use reference type data in scripting languages(jsx、vue、etc.), you can wrap it in a registered microapplication, such as Array、Function and Object. Of course, there is no need for you to format unreferenced data, because propTypes will help you to do the type conversion together.

For browser memory management, it is highly recommended to strictly distinguish reference and unreference data and avoid to wrap unreferenced data using useProps.

Here is a code example:

// Register
import magic from '@magic-microservices/magic';

const MyModule = {
  mount: (container, props) => {
    console.log('props >>> ', props);
  },
};

magic('my-application', MyModule, {
  propTypes: {
    id: Number,
    test: Boolean,
    callback: Function,
  },
});

// Use
import { useProps } from '@magic-microservices/magic';

ReactDOM.render(
  <my-application
    id="2"
    test
    callback={useProps(function () {
      return 'test';
    })}
  ></my-application>,
  MOUNT_NODE,
);

The final output in the mount function of the "my-application" in the browser is in line with expectations:

props output

Use

Use your micro-application directly via HTML tags

After registration, you can use your magic micro-application directly in the form of HTML tags. In HTML, for example:

<custom-component id="2" test></custom-component>

Or in the script (like React):

ReactDOM.render(
  <custom-component id="123" test count={count} callback={useProps(() => 'test')}></custom-component>,
  MOUNT_NODE,
);

More Repositories

1

IconPark

🍎Transform an SVG icon into multiple themes, and generate React icons,Vue icons,svg icons
TypeScript
8,298
star
2

xgplayer

A HTML5 video player with a parser that saves traffic
JavaScript
8,260
star
3

sonic

A blazingly fast JSON serializing & deserializing library
Assembly
6,870
star
4

monoio

Rust async runtime based on io-uring.
Rust
3,864
star
5

byteps

A high performance and generic framework for distributed DNN training
Python
3,603
star
6

lightseq

LightSeq: A High Performance Library for Sequence Processing and Generation
C++
3,193
star
7

ByteX

ByteX is a bytecode plugin platform based on Android Gradle Transform API and ASM. 字节码插件开发平台
Java
2,865
star
8

Elkeid

Elkeid is an open source solution that can meet the security requirements of various workloads such as hosts, containers and K8s, and serverless. It is derived from ByteDance's internal best practices.
Go
2,226
star
9

AlphaPlayer

AlphaPlayer is a video animation engine.
Java
2,181
star
10

scene

Android Single Activity Framework compatible with Fragment.
Java
2,097
star
11

bhook

🔥 ByteHook is an Android PLT hook library which supports armeabi-v7a, arm64-v8a, x86 and x86_64.
C
2,073
star
12

flutter_ume

UME is an in-app debug kits platform for Flutter. Produced by Flutter Infra team of ByteDance
Dart
2,053
star
13

terarkdb

A RocksDB compatible KV storage engine with better performance
C++
2,044
star
14

btrace

🔥🔥 btrace(AKA RheaTrace) is a high performance Android trace tool which is based on Perfetto, it support to define custom events automatically during building apk and using bhook to provider more native events like Render/Binder/IO etc.
Kotlin
1,913
star
15

gopkg

Universal Utilities for Go
Go
1,704
star
16

android-inline-hook

🔥 ShadowHook is an Android inline hook library which supports thumb, arm32 and arm64.
C
1,660
star
17

bitsail

BitSail is a distributed high-performance data integration engine which supports batch, streaming and incremental scenarios. BitSail is widely used to synchronize hundreds of trillions of data every day.
Java
1,627
star
18

go-tagexpr

An interesting go struct tag expression syntax for field validation, etc.
Go
1,470
star
19

GiantMIDI-Piano

Python
1,431
star
20

appshark

Appshark is a static taint analysis platform to scan vulnerabilities in an Android app.
Kotlin
1,363
star
21

AabResGuard

The tool of obfuscated aab resources.(Android app bundle资源混淆工具)
Java
1,307
star
22

piano_transcription

Python
1,247
star
23

CodeLocator

Kotlin
1,163
star
24

BoostMultiDex

BoostMultiDex is a solution for quickly loading multiple dex files on low Android version devices (4.X and below, SDK <21).
Java
1,106
star
25

music_source_separation

Python
1,039
star
26

Fastbot_Android

Fastbot(2.0) is a model-based testing tool for modeling GUI transitions to discover app stability problems
C++
1,031
star
27

SALMONN

SALMONN: Speech Audio Language Music Open Neural Network
Python
1,000
star
28

memory-leak-detector

C
919
star
29

fedlearner

A multi-party collaborative machine learning framework
Python
892
star
30

monolith

ByteDance's Recommendation System
Python
844
star
31

sonic-cpp

A fast JSON serializing & deserializing library, accelerated by SIMD.
C++
811
star
32

godlp

sensitive information protection toolkit
Go
770
star
33

MVDream

Multi-view Diffusion for 3D Generation
Python
744
star
34

res-adapter

Official implementation of "ResAdapter: Domain Consistent Resolution Adapter for Diffusion Models".
Python
724
star
35

bytemd

ByteMD v1 repository
TypeScript
679
star
36

tailor

C
669
star
37

ibot

iBOT 🤖: Image BERT Pre-Training with Online Tokenizer (ICLR 2022)
Jupyter Notebook
663
star
38

RealRichText

A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.
Dart
658
star
39

guide

A new feature guide component by react 🧭
TypeScript
651
star
40

mockey

a simple and easy-to-use golang mock library
Go
622
star
41

Fastbot_iOS

About Fastbot(2.0) is a model-based testing tool for modeling GUI transitions to discover app stability problems
Objective-C
553
star
42

flow-builder

A highly customizable streaming flow builder.
TypeScript
526
star
43

MVDream-threestudio

3D generation code for MVDream
Python
473
star
44

effective_transformer

Running BERT without Padding
C++
457
star
45

ByteTransformer

optimized BERT transformer inference on NVIDIA GPU. https://arxiv.org/abs/2210.03052
C++
449
star
46

Next-ViT

Python
426
star
47

matxscript

A high-performance, extensible Python AOT compiler.
C++
408
star
48

byteir

A model compilation solution for various hardware
MLIR
362
star
49

syllepsis

Syllepsis is an out-of-the-box rich text editor.
TypeScript
355
star
50

uss

This is the PyTorch implementation of the Universal Source Separation with Weakly labelled Data.
Python
324
star
51

OMGD

Online Multi-Granularity Distillation for GAN Compression (ICCV2021)
Python
323
star
52

neurst

Neural end-to-end Speech Translation Toolkit
Python
298
star
53

danmu.js

HTML5 danmu (danmaku) plugin for any DOM element
JavaScript
292
star
54

vArmor

vArmor is a cloud native container sandbox system based on AppArmor/BPF/Seccomp. It also includes multiple built-in protection rules that are ready to use out of the box.
Go
263
star
55

particle-sfm

ParticleSfM: Exploiting Dense Point Trajectories for Localizing Moving Cameras in the Wild. ECCV 2022.
C++
263
star
56

CloudShuffleService

Cloud Shuffle Service(CSS) is a general purpose remote shuffle solution for compute engines, including Spark/Flink/MapReduce.
Java
245
star
57

lynx-llm

paper: https://arxiv.org/abs/2307.02469 page: https://lynx-llm.github.io/
Python
227
star
58

g3

Enterprise-oriented Generic Proxy Solutions
Rust
227
star
59

xgplayer-vue

Vue component for xgplayer, a HTML5 video player with a parser that saves traffic
JavaScript
219
star
60

DEADiff

[CVPR 2024] Official implementation of "DEADiff: An Efficient Stylization Diffusion Model with Disentangled Representations"
Python
209
star
61

flux

A fast communication-overlapping library for tensor parallelism on GPUs.
C++
201
star
62

trace-irqoff

Interrupts-off or softirqs-off latency tracer
C
195
star
63

ParaGen

ParaGen is a PyTorch deep learning framework for parallel sequence generation.
Python
186
star
64

ByteMLPerf

AI Accelerator Benchmark focuses on evaluating AI Accelerators from a practical production perspective, including the ease of use and versatility of software and hardware.
Python
181
star
65

MoMA

MoMA: Multimodal LLM Adapter for Fast Personalized Image Generation
Jupyter Notebook
177
star
66

AWERTL

An non-invasive iOS framework for quickly adapting Right-To-Left style UI
Objective-C
175
star
67

Bytedance-UnionAD

Ruby
170
star
68

keyhouse

Keyhouse is a skeleton of general-purpose Key Management System written in Rust.
Rust
163
star
69

react-model

The next generation state management library for React
TypeScript
162
star
70

LargeBatchCTR

Large batch training of CTR models based on DeepCTR with CowClip.
Python
162
star
71

ic_flow_platform

IFP (ic flow platform) is an integrated circuit design flow platform, mainly used for IC process specification management and data flow contral.
Python
154
star
72

DanmakuRenderEngine

DanmakuRenderEngine is a lightweight and scalable Android danmaku library. 轻量级高扩展安卓弹幕渲染引擎
Kotlin
149
star
73

primus

Java
148
star
74

diat

A CLI tool to help with diagnosing Node.js processes basing on inspector.
JavaScript
146
star
75

coconut_cvpr2024

Jupyter Notebook
143
star
76

Hammer

An efficient toolkit for training deep models.
Python
138
star
77

ns-x

An easy-to-use, flexible network simulator library in Go.
Go
116
star
78

pv3d

Python
113
star
79

fc-clip

This repo contains the code for our paper Convolutions Die Hard: Open-Vocabulary Segmentation with Single Frozen Convolutional CLIP
Python
109
star
80

RLFN

Winner of runtime track in NTIRE 2022 challenge on Efficient Super-Resolution
Python
106
star
81

DCFrame

DCFrame is a Swift UI collection framework, which can easily create complex UI.
Swift
100
star
82

trace-noschedule

Trace noschedule thread
C
99
star
83

decoupleQ

A quantization algorithm for LLM
Cuda
99
star
84

tar-wasm

A faster experimental wasm-based tar implementation for browsers.
Rust
95
star
85

TWIST

Official codes: Self-Supervised Learning by Estimating Twin Class Distribution
Python
95
star
86

magic-portal

⚡ A blazing fast micro-component and micro-frontend solution uses web-components under the hood.
TypeScript
91
star
87

xgplayer-react

React component for xgplayer, a HTML5 video player with a parser that saves traffic
JavaScript
84
star
88

fe-foundation

UI Foundation for React Hooks and Vue Composition Api
TypeScript
80
star
89

nnproxy

Scalable NameNode RPC Proxy for HDFS Federation
Java
79
star
90

dbatman

Go
74
star
91

Elkeid-HUB

Elkeid HUB is a rule/event processing engine maintained by the Elkeid Team that supports streaming/offline (not yet supported by the community edition) data processing. The original intention is to solve complex data/event processing and external system linkage requirements through standardized rules.
Python
74
star
92

FreeSeg

Python
69
star
93

pull_to_refresh

Flutter pull_to_refresh widget
Dart
67
star
94

Jeddak-DPSQL

DPSQL (Privacy Protection SQL Query Service) - This project is a microservice Middleware located between the database engine ( Hive , Clickhouse , etc.) and the application system. It provides transparent SQL query result desensitization capabilities.
Python
62
star
95

terark-zip

A data structure and algorithm library built for TerarkDB
C++
62
star
96

trace-runqlat

C
61
star
97

ipmb

An interprocess message bus system built in Rust.
Rust
60
star
98

X-Portrait

Source code for the SIGGRAPH 2024 paper "X-Portrait: Expressive Portrait Animation with Hierarchical Motion Attention"
Python
59
star
99

kernel

ByteDance kernel for use on cloud.
C
57
star
100

scroll_kit

Dart
56
star