Qiankun is an implementation of Micro Frontends based on single-spa. It was developed by Ant Financial and has been widely used in many projects in Alibaba Group.
A Qiankun application consists of a main application and multiple sub applications. They each may have their own routes and this could lead to conflict in some cases.
In this post I am going to demonstrate a case of such a conflict and provide a solution for it.
At the time of writing, the latest version of qianukn is 2.10.16
.
The main app
Create the main app and install dependencies:
1 | npx create-react-app main-app |
Configure qiankun in main-app/src/index.js
:
1 | import React from "react"; |
Then add routes in main-app/src/App.js
:
1 | import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom"; |
The Sub App
Next, it’s time to create a sub app, we are using create-react-app
in this example.
1 | npx create-react-app micro-app |
Note: We don’t need to install qiankun
in our sub apps!
Then add routes configurations in micro-app/src/App.js
:
1 | import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom"; |
Add lifecycle functions in micro-app/src/index.js
:
1 | import React from "react"; |
In order to expose the sub app to the main app, additional configuration is needed for the build tool you are using. Suppose you are using webpack:
1 | const packageName = require("./package.json").name; |
In our case, there is no such file in the sub application because create-react-app
encapsulates all the npm modules it uses internally, you’ll need to run npm run eject
to get all configuration files.
Start apps
Run the following command to start the main app:
1 | npm start |
And run the same command again in the sub app, make sure your sub app is running on port 3001
.
Test our app
Open http://localhost:3000
in your browser, you will see Home
under the menu. Then, access http://localhost:3000/app1
, and the sub app will be displayed at the bottom of the page with its own menus and content. So far, so good. However, when you click on the Micro Home
link in the sub app, which points to /
, the Home
page of the main app is shown under the menus instead of what we expected. We were hoping to navigate to the home page of the sub app, not the main one.
In our case, both have a route /
with different contents. When they are working together in a system, a problem occurs.
Solution
To solve this problem, we can use a basename
in the route of the sub app.
micro-app/src/App.js
1 | function App() { |
Or even better with a conditional check:
1 | function App() { |