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

Analysis of Micro-front-end Scheme of Vue Technology Stack

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the relevant knowledge of "micro-front-end scheme analysis of Vue technology stack". The editor shows you the operation process through actual cases, and the operation method is simple, fast and practical. I hope this article "micro-front-end scheme analysis of Vue technology stack" can help you solve the problem.

Background introduction

For large front-end projects, such as the company's internal management system (generally including OA, HR, CRM, meeting reservation, etc.), if all business is put into one front-end project, the following problems will occur as business functions continue to increase:

Due to the large scale of the code, the compilation time is too long, and the speed of development and packaging is getting slower and slower.

There are more and more project files, making it more and more difficult to find related files.

A small change in a business leads to the packaging and deployment of the entire project

Scheme introduction

Preload-routes and async-routes are the micro-front-end solutions currently used by the author's team, which will eventually split the entire front-end project into a main project and multiple sub-projects, in which the two functions are as follows:

Master project: used to manage subproject routing switching, register subproject routing and global Store layer, provide global libraries and methods

Sub-project: used to develop sub-business line business code, each sub-project corresponds to a sub-business line, and contains both end (PC + Mobile) code and multiplex layer code (non-view layer in the project hierarchy)

The whole front-end project is divided into multiple sub-projects according to the business line, and each sub-project is an independent warehouse, which only contains the code of a single business line, which can be developed and deployed independently, which reduces the complexity of project maintenance.

Using this scheme, our front-end project not only maintains horizontal (multiple sub-projects) expansibility, but also has vertical (single sub-project) reusability. So how exactly did this plan come true? The implementation mechanism of the scheme is described in detail below.

Before explaining, it is clear that there are two ways to implement this scheme, one is preloaded routing, the other is lazily loaded routing, you can choose one of them according to the actual needs. Next, the implementation mechanisms of these two ways are introduced respectively.

Implementation mechanism preloading routing

Preload-routes

1. The subprojects are packaged according to the library schema of vue-cli 3 for subsequent master project references

Note: in library mode, Vue is external. This means that there will be no Vue in the package, even if you import Vue into your code. If the library is to be used by a Packer, it will try to load Vue in a dependent manner through the Packer; otherwise, it will fall back to a global Vue variable.

two。 When compiling the main project, insert the entry file main.js of the subproject into the html of the main project as a script tag through the InsertScriptPlugin plug-in

Note: be sure to place the script tag corresponding to the subproject entry file main.js on top of the script tag of the main project entry file app.js. This is to ensure that the subproject entry file executes before the main project entry file code, and the next steps will understand why.

Renote: the compiled main.js of the entry file of the project in the local development environment is saved in memory, so it is not visible on disk, but can be accessed.

The core code of InsertScriptPlugin is as follows:

Compiler.hooks.compilation.tap ('InsertScriptWebpackPlugin', compilation = > {compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tap (' InsertScriptWebpackPlugin', htmlPluginData = > {const {assets: {js}}) = htmlPluginData / / insert the incoming js into the html in the form of a script tag / / Note: the entry file main.js of the subproject needs to be placed before the main project entry file app.js, because the subproject needs to register its own route list to the global js.unshift in advance (. Self.files);});})

3. The html of the main project needs to be forwarded by proxy to access the compiled js / css and other resources in the subproject.

If you are developing locally, you can use the proxy provided by webpack, for example:

Const PROXY = {'/ app-a/': {target: 'http://localhost:10241/'}}

If it is an online deployment, it can be forwarded through nginx or the packaged main project and subprojects can be referenced in a folder according to the relative path.

4. When the browser parses the html, it parses and executes the entry file main.js to the subproject, registering the route list of the subproject with the Vue.share.routes so that the subsequent master project merges it into the overall route.

The main.js code of the sub-project is as follows: (in order to minimize the resources loaded when the first main project page is rendered, it is recommended that the entry file of the sub-project should only be routed and mounted)

Import Vue from 'vue';import routes from'. / routes';const share = (Vue.__share__ = Vue.__share__ | | {}); const routesPool = (share.routes = share.routes | | {}); / / Mount the route list of the subproject to the Vue.__share__.routes so that the subsequent master project will merge it into the total route routesPool [process.env.VUE _ APP_NAME] = routes

5. Continue to parse html downwards. When parsing and executing to the main project main.js, get the route list of all subprojects from Vue.share.routes, merge it into the overall routing table, initialize a vue-router instance, and pass it into the new Vue.

The related key codes are as follows

/ / get the route list of all sub-projects from Vue.__share__.routes and merge them into the overall routing table const routes = Vue.__share__.routes;export default new Router ({routes: Object.values (routes). Reduce ((acc, prev) = > acc.concat (prev), [{path:'/', redirect:'/ app-a'}])})

At this point, the single-page application is divided into multiple sub-projects according to the business. To put it bluntly, the entry file main.js of the sub-project is the bridge between the main project and the sub-project.

In addition, if you need to use vuex, the order is the opposite of vue-router (main project first, then subproject):

1. First initialize a store instance new Vuex.Store in the entry file of the main project, and then hang it on Vue.__share__.store

two。 Then get the Vue.__share__.store in the App.vue of the sub-project and call store.registerModule ('app-x', store) to register the store of the sub-project as a sub-module on the store

Lazy loading routing mode

Async-routes

Lazy loading route, as the name implies, means waiting for the user to click to enter the sub-project module, parsing the route to jump to determine which sub-project is, and then asynchronously loading the entry file main.js of the sub-project (you can use systemjs or write a method to dynamically create script tags and insert body). After loading successfully, the route of the subproject can be dynamically added to the total route of the main project.

1. The main project router.js file defines the beforeEach hook in vue-router to intercept the route, and analyzes which sub-project is needed according to the route to be redirected, and then loads the corresponding sub-project entry file asynchronously. The following is the core code:

Const cachedModules = new Set (); router.beforeEach (async (to, from, next) = > {const [, module] = to.path.split ('/'); if (Reflect.has (modules, module)) {/ / if the corresponding subproject has already been loaded, if (! cachedModules.has (module)) {const {default: application} = await window.System.import (modules [module]) without repeated loading If (application & & application.routes) {/ / dynamically add route-list router.addRoutes (application.routes) of subprojects;} cachedModules.add (module); next (to.path);} else {next ();} return;}})

two。 The entry file main.js of the subproject only needs to expose the routes of the subproject to the main project, as follows:

Import routes from'. / routes';export default {name: 'javascript', routes, beforeEach (from, to, next) {console.log (' _ javascript:', from.path, to.path); next ();}}

Note: in addition to exposing the routes method, the beforeEach method is also exposed here, which is to support the restriction of page permissions on the sub-project through the route guard. The beforeEach of this sub-project obtained by the main project can be executed in the beforeEach hook of vue-router. For more information, please see async-routes.

Except that the interaction between the main project and the subproject is different, the agent forwarding subproject resources, vuex store registration, and so on are exactly the same as the preloaded route above.

Advantages and disadvantages

Let's talk about the pros and cons of this scheme:

Advantages

Sub-projects can be packaged and deployed separately, which improves the speed of development and packaging.

The development of sub-projects is independent and independent of each other, and can be maintained in different warehouses, reducing the size of a single project.

Maintain the experience of single-page application, switching between sub-projects without refresh

The cost of transformation is low, the invasion of existing projects is low, and the cost of business line migration is also low.

Ensure that the whole project is unified with one technology stack.

Disadvantages:

The main project and subprojects need to share a Vue instance, so it is not possible for a subproject to use the latest version of Vue (such as Vue3) or React alone.

Partial answer to the question

1. If the subproject code is updated, do you need to package and deploy the main project in addition to the package deployment subproject?

There is no need to update the deployment master project. There is a trick that I forgot to mention above, that is, the packaged entry file of the sub-project does not add chunkhash, it is directly main.js (all other js of the sub-project have chunkhash). In other words, the main project only needs to remember the name of the subproject to find the entry file of the subproject through subapp-name/main.js, so after the subproject is packaged and deployed, the main project does not need to update anything.

two。 For the second problem, how to prevent the sub-project entry file main.js from being cached all the time if it does not use chunkhash?

You can set the cache to be not cached on the static resource server for sub-project entry files. The following is the relevant configuration of the server for nginx:

Location / {set $expires_time 7d;... If ($request_uri ~ *\ / (contract | meeting | crm)-app\ / main.js (\?. *)? $) {# set expires_time-1 for the entry file, that is, expire is-1s of server time and always expires set $expires_time-1;} expires $expires_time;.} this is the end of the introduction on "Micro-front-end solution Analysis of Vue Technology Stack". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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