### Install Project Dependencies with Yarn
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/README.md
Run this command to install all necessary project dependencies before starting development.
```bash
yarn install
```
--------------------------------
### Clone and Run Project
Source: https://github.com/jd-opensource/micro-app/blob/master/DEVELOP.md
Clone the repository, install dependencies using yarn bootstrap, and start all applications with yarn start. The default base application is main-react16, and sub-applications include react16, react17, vue2, vue3, angular11, and vite.
```bash
git clone https://github.com/jd-opensource/micro-app.git
cd micro-app
// install dependencies
yarn bootstrap
// run project
yarn start
```
--------------------------------
### Run micro-app project
Source: https://github.com/jd-opensource/micro-app/blob/master/README.md
Start the micro-app project locally for development. This command runs the project after dependencies have been installed.
```bash
yarn start
```
--------------------------------
### Install micro-app with Yarn
Source: https://github.com/jd-opensource/micro-app/blob/master/README.md
Install the micro-app package using Yarn. This is the first step for setting up the base application.
```bash
yarn add @micro-zoe/micro-app
```
--------------------------------
### Start Ant Design Pro Project
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/main-react16/README.md
Run this command to start the development server for Ant Design Pro.
```bash
npm start
```
--------------------------------
### Install micro-app via npm, yarn, or pnpm
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Install the micro-app package using your preferred package manager.
```bash
# npm
npm install @micro-zoe/micro-app --save
```
```bash
# yarn
yarn add @micro-zoe/micro-app
```
```bash
# pnpm
pnpm add @micro-zoe/micro-app
```
--------------------------------
### Start Main Vue2 Base Application
Source: https://github.com/jd-opensource/micro-app/blob/master/DEVELOP.md
To start the main-vue2 base application specifically, use the command yarn start:main-vue2.
```bash
yarn start:main-vue2
```
--------------------------------
### Start micro-app in main entry
Source: https://github.com/jd-opensource/micro-app/blob/master/README.md
Import and start the micro-app framework in your main application entry point. This initializes the framework for rendering micro applications.
```javascript
// main.js
import microApp from '@micro-zoe/micro-app'
microApp.start()
```
--------------------------------
### Install Project Dependencies with PNPM
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/main-vite/README.md
Installs all necessary project dependencies. Ensure you have PNPM installed globally.
```sh
pnpm install
```
--------------------------------
### Install dependencies for micro-app development
Source: https://github.com/jd-opensource/micro-app/blob/master/README.md
Install project dependencies after cloning the repository. This command is used for local development and contribution.
```bash
yarn bootstrap
```
--------------------------------
### Install Node Modules
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/main-react16/README.md
Install project dependencies using npm or yarn.
```bash
npm install
```
```bash
yarn
```
--------------------------------
### Start Development Server with Hot Reloading
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/README.md
Use this command to compile Vue 2 project assets and start a local development server with hot-reloading enabled.
```bash
yarn serve
```
--------------------------------
### Start Main React16 Application
Source: https://github.com/jd-opensource/micro-app/blob/master/DEVELOP.md
To run the main-react16 application in isolation, navigate to its directory (dev/main-react16/) and execute yarn start.
```bash
cd dev/main-react16/
yarn start
```
--------------------------------
### Run micro-app Locally
Source: https://github.com/jd-opensource/micro-app/blob/master/README.zh-cn.md
Start the micro-app project locally using the yarn start command. The default access address is http://localhost:3000.
```bash
yarn start # 访问 http://localhost:3000
```
--------------------------------
### Start React16 Sub-Application
Source: https://github.com/jd-opensource/micro-app/blob/master/DEVELOP.md
To run a specific sub-application like react16 in isolation, navigate to its directory (dev/children/react16/) and execute yarn start.
```bash
cd dev/children/react16
yarn start
```
--------------------------------
### Clone micro-app repository
Source: https://github.com/jd-opensource/micro-app/blob/master/README.md
Clone the micro-app project repository from GitHub to contribute or develop locally. This is the first step in the development setup.
```bash
git clone https://github.com/jd-opensource/micro-app.git
```
--------------------------------
### Dynamically Load Script Example (Commented Out)
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/public/index.html
This commented-out section shows how to dynamically create and append a script tag to the document body, which would then execute its content, including an eval statement.
```javascript
const dynamicScript = document.createElement('script')
dynamicScript.textContent = `eval('console.log("动态创建的script的eval", window)')`
document.body.appendChild(dynamicScript)
```
--------------------------------
### Run Vite Development Server
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/main-vite/README.md
Starts the Vite development server, enabling hot-reloading for rapid development. This command is used during the development phase.
```sh
pnpm dev
```
--------------------------------
### Add Angular Material to Project
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/angular14/src/app/home/home.component.html
Integrate Angular Material components into your project using this command. It handles necessary installations and configurations.
```bash
ng add @angular/material
```
--------------------------------
### UMD Mode Lifecycle Exports for Vue 3
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Vue 3 sub-applications in UMD mode need to export `mount` and `unmount` functions. This example demonstrates how to initialize and destroy the Vue app instance within these lifecycle hooks.
```javascript
// sub-app main.js (Vue 3 + UMD mode)
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
let app = null
if (!window.__MICRO_APP_ENVIRONMENT__) {
app = createApp(App).use(router)
app.mount('#app')
}
export function mount () {
app = createApp(App).use(router)
app.mount(window.__MICRO_APP_ENVIRONMENT__ ? '#app' : document.body)
}
export function unmount () {
app?.unmount()
app = null
}
```
--------------------------------
### Asynchronous Operation in Module Script
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vite4/index.html
An example of an asynchronous operation within an HTML script tag marked as a module.
```javascript
await new Promise(resolve=>setTimeout(resolve, 100))
```
--------------------------------
### UMD Mode Lifecycle Exports for React
Source: https://context7.com/jd-opensource/micro-app/llms.txt
In UMD mode, React sub-applications must export `mount` and `unmount` functions for micro-app to manage their lifecycle. This example shows how to render the React app within these hooks.
```javascript
// sub-app main.js (React + UMD mode)
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
let root = null
// Normal render on first load (non-micro-app context)
if (!window.__MICRO_APP_ENVIRONMENT__) {
root = ReactDOM.createRoot(document.getElementById('root'))
root.render()
}
// UMD lifecycle hooks — called by micro-app on mount/unmount
export function mount () {
const container = document.getElementById('root')
root = ReactDOM.createRoot(container)
root.render()
console.log('sub-app mounted via UMD')
}
export function unmount () {
root?.unmount()
root = null
console.log('sub-app unmounted via UMD')
}
```
--------------------------------
### microApp.start(options)
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Initializes the micro-app framework by registering the `` custom element and bootstrapping the system. This method must be called once before any `` tags are rendered. It accepts an optional configuration object to set global defaults for various framework features.
```APIDOC
## microApp.start(options) — Initialize the framework
Registers the `` custom element and bootstraps the framework. Must be called once before any `` tag is rendered. Accepts an optional `OptionsType` configuration object to set global defaults.
```js
// main.js (base application entry)
import microApp from '@micro-zoe/micro-app'
microApp.start({
tagName: 'micro-app', // custom element tag name (default: 'micro-app')
iframe: false, // use iframe sandbox globally (default: false → with-sandbox)
inline: false, // run JS in inline
```
```jsx
// React JSX (base app)
import { useEffect, useRef } from 'react'
import 'zone.js' // only needed for Angular sub-apps
export default function Page() {
const appRef = useRef(null)
useEffect(() => {
// Pass data programmatically
if (appRef.current) appRef.current.data = { token: 'abc123' }
}, [])
return (
)
}
```
**Available element attributes:**
| Attribute | Type | Description |
|---|---|---|
| `name` | string | **Required.** Unique app identifier |
| `url` | string | **Required.** Sub-app entry HTML URL |
| `baseroute` | string | Route prefix for sub-app |
| `router-mode` | `search`|`state`|`pure`|`native` | Virtual router mode (default: `search`) |
| `default-page` | string | Default page path on mount |
| `keep-alive` | boolean | Keep DOM alive when unmounted |
| `destroy` | boolean | Delete cached resources on unmount |
| `iframe` | boolean | Use iframe sandbox instead of with-sandbox |
| `inline` | boolean | Run JS in inline script mode |
| `disable-scopecss` | boolean | Disable CSS scoping |
| `disable-sandbox` | boolean | Disable JS sandbox entirely |
| `disable-patch-request` | boolean | Skip request URL rewriting |
| `keep-router-state` | boolean | Restore router state on remount |
| `ssr` | boolean | Enable SSR mode |
| `fiber` | boolean | Run JS execution in fiber (async) chunks |
| `clear-data` | boolean | Clear event data on unmount |
| `shadowDOM` | boolean | Use native ShadowDOM |
```
--------------------------------
### Check Code Style with Lint
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/main-react16/README.md
Use this command to check the code style according to the project's linting rules.
```bash
npm run lint
```
--------------------------------
### Check Vue Instance and Log
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/public/index.html
This script checks if the Vue instance is available globally and logs its presence. It also includes an eval statement within a try-catch block for logging.
```javascript
console.log('window.Vue: ', window.Vue, 'Vue in window: ', 'Vue' in window) ;eval('console.log("html自带script的eval", window)')
```
--------------------------------
### Include symbol JS file
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/src/my-font/demo_index.html
Include the generated iconfont.js file in your HTML to use Symbol icons.
```html
```
--------------------------------
### Lint and Fix Code Files
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/README.md
Run this command to lint your project files and automatically fix any style or formatting issues.
```bash
yarn lint
```
--------------------------------
### Sub-App Environment Variables
Source: https://context7.com/jd-opensource/micro-app/llms.txt
micro-app injects several global variables into the sub-application's sandboxed window. These variables provide information about the micro-app environment, such as the app name, base URL, public path, and base route, enabling conditional logic and runtime configurations.
```APIDOC
## Sub-App Environment Variables
micro-app injects several global variables into the sub-application's sandboxed window for introspection and conditional logic.
```js
// sub-app — detect if running inside micro-app
if (window.__MICRO_APP_ENVIRONMENT__) {
console.log('Running inside micro-app sandbox')
console.log('App name:', window.__MICRO_APP_NAME__) // 'order-center'
console.log('Base URL:', window.__MICRO_APP_BASE_URL__) // 'http://localhost:3000'
console.log('Public path:', window.__MICRO_APP_PUBLIC_PATH__) // 'http://localhost:3001/'
console.log('Base route:', window.__MICRO_APP_BASE_ROUTE__) // '/order'
}
// Sub-app: configure webpack public path at runtime
// In webpack entry file (before any imports):
if (window.__MICRO_APP_ENVIRONMENT__) {
__webpack_public_path__ = window.__MICRO_APP_PUBLIC_PATH__
}
// Vite sub-app — set base path
// vite.config.js
export default {
base: window.__MICRO_APP_ENVIRONMENT__
? window.__MICRO_APP_PUBLIC_PATH__
: '/',
server: {
headers: { 'Access-Control-Allow-Origin': '*' },
},
}
```
```
--------------------------------
### Programmatically Unmount Sub-Applications
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Unmount a running sub-application from code using `unmountApp`. Options include soft unmount, hard destroy, and clearing keep-alive state or data.
```javascript
// Soft unmount — keeps cached resources for fast remount
microApp.unmountApp('order-center').then((ok) => {
console.log('unmounted:', ok)
})
// Hard destroy — clears all cached resources and event data
microApp.unmountApp('order-center', {
destroy: true, // delete cached JS/CSS resources
clearData: true, // clear event center data
clearAliveState: false,
}).then((ok) => {
console.log('destroyed:', ok)
})
// Unmount a keep-alive app (clear its alive state without full destroy)
microApp.unmountApp('dashboard', {
clearAliveState: true,
clearData: true,
}).then(ok => console.log('keep-alive cleared:', ok))
// Unmount every registered sub-app sequentially
microApp.unmountAllApps({ destroy: true }).then(() => {
console.log('all sub-apps destroyed')
})
```
--------------------------------
### Generate New Component with Angular CLI
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/angular14/src/app/home/home.component.html
Use this command to generate a new component in your Angular project. Specify the component name as an argument.
```bash
ng generate component xyz
```
--------------------------------
### Add general CSS for Symbol icons
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/vue2/src/my-font/demo_index.html
This CSS provides basic styling for Symbol icons, allowing them to be sized and colored like fonts.
```css
```
--------------------------------
### Query Active and All Registered Apps
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Use `getActiveApps` and `getAllApps` to query the state of registered sub-applications. `getActiveApps` can optionally exclude hidden or pre-rendered applications.
```javascript
import { getActiveApps, getAllApps } from '@micro-zoe/micro-app'
// All registered app names (includes unmounted, prefetch, hidden)
const all = getAllApps()
console.log(all) // ['dashboard', 'order-center', 'settings']
// Currently active apps (mounted and visible)
const active = getActiveApps()
console.log(active) // ['order-center']
// Exclude hidden keep-alive apps and pre-render apps
const strictActive = getActiveApps({
excludeHiddenApp: true,
excludePreRender: true,
})
console.log(strictActive) // ['order-center']
```
--------------------------------
### Add Dependency to Angular Project
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/angular11/src/app/first/first.component.html
Use this placeholder command to add a dependency to your Angular project. Replace '____' with the actual package name.
```bash
ng add ____
```
--------------------------------
### Base App Data Communication with Micro-Apps
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Utilize `microApp.setData` to send data to a specific sub-application and `microApp.getData` to retrieve data sent by a sub-application. Listeners can be added and removed for real-time data updates.
```js
// base app — send data to sub-app named 'order-center'
microApp.setData('order-center', {
userId: 101,
permissions: ['read', 'write'],
theme: 'dark',
})
// Force dispatch even if data is unchanged
microApp.forceSetData('order-center', { timestamp: Date.now() })
// Read latest data that 'order-center' sub-app has sent up
const subAppData = microApp.getData('order-center')
console.log(subAppData) // { cartCount: 3, lastRoute: '/order/list' }
// Read data that base app previously sent to 'order-center'
const sentData = microApp.getData('order-center', true)
// Listen for data dispatched by 'order-center' sub-app
microApp.addDataListener('order-center', (data) => {
console.log('Received from order-center:', data)
}, /* autoTrigger= */ true)
// Stop listening
microApp.removeDataListener('order-center', myListener)
// Clear all listeners for an app
microApp.clearDataListener('order-center')
// Clear stored data
microApp.clearData('order-center')
```
--------------------------------
### Add PWA Support with Angular CLI
Source: https://github.com/jd-opensource/micro-app/blob/master/dev/children/angular14/src/app/home/home.component.html
Enable Progressive Web App (PWA) features for your Angular application by running this command. It sets up service workers and manifest files.
```bash
ng add @angular/pwa
```
--------------------------------
### Configure Cross-Origin for Sub-application (Development)
Source: https://github.com/jd-opensource/micro-app/blob/master/README.zh-cn.md
Configure webpack-dev-server headers to support cross-origin requests for sub-applications during development.
```javascript
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
},
}
```
--------------------------------
### Navigate within Sub-Apps using microApp.router
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Programmatically navigate between sub-applications using pushState or replace history. Supports back, forward, and go navigation. Retrieves current sub-app location.
```javascript
const { router } = microApp
// Navigate inside 'order-center' sub-app (pushState)
router.push({ name: 'order-center', path: '/order/detail?id=99' })
.then(() => console.log('navigation complete'))
.catch(err => console.error('navigation failed:', err))
// Replace current history entry
router.replace({ name: 'order-center', path: '/order/list', replace: true })
// Standard history navigation
router.back()
router.forward()
router.go(-2)
// Get current location of a sub-app
const currentLocation = router.current.get('order-center')
console.log(currentLocation?.pathname) // '/order/list'
```
--------------------------------
### microApp.router - Virtual Router API
Source: https://context7.com/jd-opensource/micro-app/llms.txt
The virtual router system manages the routing of all sub-applications. The base app can programmatically navigate inside any sub-app, set navigation guards, and sync sub-app routes to the browser URL.
```APIDOC
## microApp.router — Virtual Router API
The virtual router system manages the routing of all sub-applications. The base app can programmatically navigate inside any sub-app, set navigation guards, and sync sub-app routes to the browser URL.
```js
const { router } = microApp
// Navigate inside 'order-center' sub-app (pushState)
router.push({ name: 'order-center', path: '/order/detail?id=99' })
.then(() => console.log('navigation complete'))
.catch(err => console.error('navigation failed:', err))
// Replace current history entry
router.replace({ name: 'order-center', path: '/order/list', replace: true })
// Standard history navigation
router.back()
router.forward()
router.go(-2)
// Get current location of a sub-app
const currentLocation = router.current.get('order-center')
console.log(currentLocation?.pathname) // '/order/list'
// Navigation guard — runs before every sub-app navigation
const removeBeforeGuard = router.beforeEach((to, from, appName) => {
console.log(`[${appName}] navigating: ${from?.pathname} → ${to.pathname}`)
})
// Navigation guard — runs after every sub-app navigation
router.afterEach((to, from, appName) => {
analytics.track('page_view', { app: appName, path: to.pathname })
})
// Remove guard
removeBeforeGuard()
// Accurate guard — only fires for a specific sub-app
router.beforeEach({
'order-center': (to, from) => {
if (to.pathname === '/order/admin' && !user.isAdmin) {
router.replace({ name: 'order-center', path: '/order/list' })
}
}
})
// Set default landing page for sub-app on next mount
const removeDefault = router.setDefaultPage({ name: 'order-center', path: '/order/list' })
// Remove it later
router.removeDefaultPage('order-center')
removeDefault() // alternative removal via returned function
// Sync sub-app route into browser URL (search/state mode)
router.attachToURL('order-center')
// Sync all active sub-apps to browser URL at once
router.attachAllToURL({ includeHiddenApp: false, includePreRender: false })
// Allow sub-app to navigate base app (pass base router instance)
import { useRouter } from 'vue-router'
const baseRouter = useRouter()
router.setBaseAppRouter(baseRouter)
// Encode/decode sub-app path for URL embedding
const encoded = router.encode('/order/detail?id=99')
const decoded = router.decode(encoded)
```
```
--------------------------------
### microApp.unmountApp / unmountAllApps - Programmatic Unmount
Source: https://context7.com/jd-opensource/micro-app/llms.txt
Unmount a running sub-application from code, with options for destroy mode, keep-alive clearing, and data cleanup.
```APIDOC
## microApp.unmountApp / unmountAllApps — Programmatic Unmount
Unmount a running sub-application from code, with options for destroy mode, keep-alive clearing, and data cleanup.
```js
// Soft unmount — keeps cached resources for fast remount
microApp.unmountApp('order-center').then((ok) => {
console.log('unmounted:', ok)
})
// Hard destroy — clears all cached resources and event data
microApp.unmountApp('order-center', {
destroy: true, // delete cached JS/CSS resources
clearData: true, // clear event center data
clearAliveState: false,
}).then((ok) => {
console.log('destroyed:', ok)
})
// Unmount a keep-alive app (clear its alive state without full destroy)
microApp.unmountApp('dashboard', {
clearAliveState: true,
clearData: true,
}).then(ok => console.log('keep-alive cleared:', ok))
// Unmount every registered sub-app sequentially
microApp.unmountAllApps({ destroy: true }).then(() => {
console.log('all sub-apps destroyed')
})
```
```