Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case study of micro-front-end qiankun project practice

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "case study of micro-front-end qiankun project practice". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "micro-front-end qiankun project practice case study" bar!

So what is qiankun?

Qiankun is a single-spa-based micro-front-end implementation library that aims to help you build a production-usable micro-front-end architecture system more easily and painlessly.

What is a micro front end?

The micro front-end architecture has the following core values:

Technology stack independent

The main framework does not limit the technology stack of access applications, and micro-applications have full autonomy.

Independent development and deployment

The micro-application repository is independent, the front and rear end can be developed independently, and the main framework is updated synchronously automatically after deployment.

Incremental upgrade

In the face of various complex scenarios, it is usually difficult for us to upgrade or restructure the technology stack of an existing system, and the micro-front end is a very good means and strategy to implement progressive reconstruction.

Stand-alone runtime

The state of each micro-application is isolated, and the runtime state is not shared.

Extracted from the official qiankun documentation

Main application configuration

The main application and sub-application of this project are both vue.

Download qiankun

Npm install qiankun

Register a micro-application in the main application

/ / Import Qiankun function

Import {registerMicroApps, setDefaultMountApp, start} from "qiankun"

Encapsulating render method

This method needs to be called initially in main.js, which is mainly used to load the main application, and then the sub-application is called in turn, so it pretends to judge. The passed parameters are the HTML and load status content fields of the sub-application. We use vuex to store them for ease of use.

Let app = null; function render ({appContent, loading}) {if (! app) {app = new Vue ({router, store, render: h = > h (App),}). $mount ('# app');} else {store.commit ('microApp/changeCenter', appContent); store.commit (' microApp/changeLoading', loading);}}

Micro-application registration

The apps below can be used to obtain the post-data. Registering the micro-application case is relatively simple and convenient for everyone to understand.

In the registration of self-application parameters * * container and render** step on the pit more, the following will focus on.

Function genActiveRule (routerPrefix) {return location = > location.pathname.startsWith (routerPrefix) } / / data passed to the sub-application let msg = {! [] (https://user-gold-cdn.xitu.io/2020/4/27/171bbc5de042ec98?w=1811&h=959&f=gif&s=4951066) data:' practices the bitterness of love and learns to put away the previous longing'} let apps = [{name: 'linjunjie', entry:' / / localhost:215' / / change the port number of your sub-application container:'#subView', / / node id / / sandboxie mode / / render:render, / / normal mode activeRule: genActiveRule ('/ star'), props:msg}] / / the registered sub-application parameter is array registerMicroApps (apps) {beforeLoad: [app = > {console.log (app) console.log ('[LifeCycle] before load% c% slots, 'color: green ', app.name);},], beforeMount: [app = > {console.log (' [LifeCycle] before mount% c% slots, 'color: green;', app.name);},], afterUnmount: [app = > {console.log (' [LifeCycle] after unmount% c% slots, 'color: green;', app.name);},],}) SetDefaultMountApp ('/ star/linjunjie') / / enable sandboxie mode start ({sandbox: {strictStyleIsolation: true}})

When the micro-application information is registered, once the url of the browser changes, the matching logic of the qiankun will be automatically triggered, and all the micro-applications on the matching of activeRule rules will be inserted into the specified container, and the life cycle hooks exposed by the micro-applications will be called in turn.

Display elements prepared by the main application for the sub-application

Lin Junjie Zhang Yixing import {mapState} from 'vuex' Export default {data () {return {}}, computed: {/ / get sub-application HTML data... mapState ('microApp', [' content']),... mapState ('microApp', [' mircoAppLoading']),} Methods: {/ / define jump method onChangePage (url) {console.log (url) this.routerGo (url,'my favorite male star')}, routerGo (href ='/', title = null, stateObj = {}) {window.history.pushState (stateObj, title, href) },}}

Sub-application configuration

The configuration of the sub-application is relatively simple, and you don't need to download qiankun to export the life hook.

Export the life hook of the response

Three life cycle hooks, bootstrap, mount and unmount, are exported for the master application to call at an appropriate time. Note that when instantiating a route, it is judged that the route should be prefixed when running in the qiankun environment. The prefix is consistent with the parameters in the main application registration sub-application function genActiveRule ("/ subdemo").

'The star' value needs to correspond to the value of the main application. The value in genActiveRule ("/ star") needs to be agreed to be used by both the main application and the micro application.

If new VueRouter is not configured in main.js, move this configuration to main.js for easy management

Import routes from'. / router' / / it is convenient to export routing information using let router = null; let instance = null; function render (props = {}) {const {container} = props; router = new VueRouter ({base: window.__POWERED_BY_QIANKUN__?'/ star':'/', mode: 'history', routes,}) Instance = new Vue ({router, store, render: h = > h (App),}). $mount (container? Container.querySelector ('# app'):'# app');} if (! window.__POWERED_BY_QIANKUN__) {render ();} export async function bootstrap () {console.log ('[vue] vue app bootstraped');} export async function mount (props) {/ / props contains the parameters passed by the main application as well as the node information console.log (props) render (props) created for the sub-application } export async function unmount () {instance.$destroy (); instance = null; router = null;}

Configure packaging tools for micro-applications

In addition to the corresponding lifecycle hooks exposed in the code, in order for the master application to correctly identify some information exposed by micro-applications, the packaging tools of micro-applications need to be configured in vue.config.js as follows:

Const packageName = require ('. / package.json'). Name; module.exports = {output: {library: `${packageName}-[name]`, libraryTarget: 'umd', jsonpFunction: `webpackJsonp_$ {packageName}`,},}

Sub-application judgment

New publicPath.js in sub-application is introduced in main.js

If (window.__POWERED_BY_QIANKUN__) {/ / processing resource _ _ webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;}

Dealing with resource loading problems

Configure vue.config.js

Module.exports = {publicPath: `/ / localhost:$ {port}`,}

Complete configuration of vue.config.js

Const path = require ('path'); const packageName = require ('. / package'). Name; function resolve (dir) {return path.join (_ _ dirname, dir);} const port = 7101 / / dev port module.exports = {publicPath: `/ localhost:$ {port}`, outputDir: 'dist', assetsDir:' static', filenameHashing: true, devServer: {/ / host: '0.0.0.0, hot: true, historyApiFallback: true,// add key port, overlay: {warnings: false, errors: true,} Headers: {'Access-Control-Allow-Origin':' *',},}, configureWebpack: {resolve: {alias: {'@': resolve ('src'),},}, output: {library: `${packageName}-[name]`, libraryTarget:' umd', jsonpFunction: `webpackJsonp_$ {packageName}` },},}

Trampling record

Refresh page 404 when the current page is a sub-application

The following methods are configured for the main application

Method one: delete the mode configuration item

Mode: 'history', / / remove this configuration code

Mode 2 configure 404 page

If mode is not commented out: 'history' this parameter redirects the 404 page to the home home page

{path:'*', name: 'indexNotFound', component: resolve = > require ([' @ / components/home'], resolve), children: HomeChild,}

Problems encountered in sub-application style isolation to start sandbox mode

Main application configuration sandbox: {strictStyleIsolation: true} rendering mode is changed from render mode to containercontainer:'#subView',. At this time, the mount dom of the sub-application is to keep in mind the main container: # + id

Sub-application configuration mentioned above about the main code interception

Instance = new Vue ({router, store, render: h = > h (App),}). $mount (container? Container.querySelector ('# app'):'# app'); / / focus

Problem encountered: open sandbox mode, if you use render mode, you will get an error, so choose container mode

At this point, I believe that everyone has a deeper understanding of the "micro-front-end qiankun project practice case analysis", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report