current position:Home>Vue3 + ant design Vue + Python realizes the combined deployment of a set of code and multiple sub applications

Vue3 + ant design Vue + Python realizes the combined deployment of a set of code and multiple sub applications

2022-02-02 07:23:04 liuliu6724650

Let me write it out front  

The main solution of this paper is : How to be in Different servers When deployed above , Package and compile different src Folder ( file ), To deploy different contents according to a set of code and project requirements .

Technology stack used :Vue3、Ant Design Vue、Python( Mainly used in deployment , Not necessary ).

principle : utilize python and shell Command to copy files on demand , Combined into the file structure required for our project deployment .

This article will not Vue3 and Ant Design Vue Do the details above , If necessary , You can leave a message to the author .

This article assumes that you already know and understand Vue Related basic knowledge of .

Where is the use ?

When your project needs to deploy different sub applications according to different customer needs , This deployment method may be used .

There is a doubt : Why not iframe perhaps Heaven and earth ?

Front end microservices It can really solve the appeal demand , And it also has a good user experience , All of them don't use microservices , The main reasons are as follows :

  1. The heaven and earth document clearly states : With  vue-cli 3+  Generated  vue 2.x  Project as an example ,vue 3  The version will be supplemented after it is stable .
  2. Height of sub application UI Integration and logic reuse .
  3. The front end will occupy a lot of ports .
  4. Unified management of code .

If you're right Front end microservices Interested in , You can check the document step by step .

Directory structure

in order to Python Better handling of files during automatic deployment , The requirements for the unity of directory structure are relatively high .

For example, our project has 3 Subsystem ( All the examples below focus on these three sub applications ), Respectively demo1,demo2,demo3, Then our project structure is correct :

 Catalog 1.png

public

There is an important The configuration file :

public/config/global.js

var globalConfig = {
    /**
     *  Deployment mode , Default full
     */
    deployName: '',
}
window.globalConfig = globalConfig
 Copy code 

Then put this file in index.html Introduction in

Mount it to window The meaning of is that every page can be used window To get the value , Next, we will explain the function of this file .

api

Pictured above , We will put the list of interfaces used by each sub application in different folders , And there is one called index.ts The file of ( Later we will explain why we should name it like this )

api There is a... Under the root of the folder index.ts yes axios Corresponding interception global configuration , There is no expansion here , If you have any questions here, you can baidu by yourself .

components

This folder is mainly some public components used by different sub applications . There are no special requirements for naming here .

layouts

This folder is mainly some layout methods used by different sub applications . There are no special requirements for naming here .

router

Pictured above , We will put the routes of each sub application in different folders , And there is one called index.ts The file of ( Later we will explain why we should name it like this )

store

This folder is mainly used by different sub applications vuex. There are no special requirements for naming here .

utils

This folder is mainly a public method used by different sub applications . There are no special requirements for naming here .

views

Pictured above , We will put the pages of each sub application in different folders ,views The following root folder should be named after api,router bring into correspondence with ( Later we will explain why we should name it like this )

These are some naming rules for all folders , All of it api,router There is a folder called index.ts, Look at the following code :

router/demo1/index.ts

export const demo1: any = [
    {
        path: '/demo1-index',
        name: 'demo1-index',
        redirect: '/base-index/index',
        meta: {
            title: 'demo1',
        },
        component: () => import('@/layouts/content.vue'),
        children: [
            {
                path: '/demo1-index/index',
                name: 'base-index-index',
                meta: {},
                component: () => import('@/views/demo1/index.vue'),
            },
        ],
    },
]

router/subImport.js

//  Full application deployment 
const fullFn = () => {
    return {
        demo1: require('./demo1').demo1, 
        demo2: require('./demo2').demo2,
        demo3: require('./demo3').demo3,
    }
}
//  Some sub application deployment ( For example, deployment demo1,demo2)
const bufenFn = () => {
    return {
        demo1: require('./demo1').demo1, 
        demo2: require('./demo2').demo2,
    }
}

const result = []

switch (window.globalConfig.deployName) {
    case 'bufen':
        for (const value of Object.values(bufenFn())) {
            if (value) {
                result.push(...value)
            }
        }
        break;
    default:
        for (const value of Object.values(fullFn())) {
            if (value) {
                result.push(...value)
            }
        }
        break;
}
export default result
 Copy code 

All file names are uniformly named index.ts, Because it can be abbreviated , If the names don't match , So the next python Dynamically adding files will It is difficult to Handle

Python Processing documents

The picture below is python What is needed below py file :  Wechat screenshot _20211215145911.png

General process : Create a... At the root of the project export Folder , Used to store all files copied on demand , And then in export Folder npm run build Output dist file ( The front-end deployment of our company is fully automated , With jenkins and docker, Combined with this process, the front-end deployment can be one click )

Specific process :

  1. First determine whether the root has export Folder , Create if not , If yes, delete it first and create it later , Guarantee export Folders are clean before copying files
python/index.py

#!/usr/bin/python

import os

import utils
import func

def startCopy():
    utils.del_file("export")
    func.copyConfigs()
    
if os.path.exists("export"):
    startCopy()
else: 
    os.makedirs("export") 
    startCopy()
 Copy code 

del_file Method is a custom method to delete files and folders

copyConfigs Is the specific method of copying files 2. perform copyConfigs Method , Copy file . The core step

Before copying , We need to meet the requirements of our project , To configure copyConfigs Method required parameters

python/configs.py

import sys
#  Public configuration items 
basecfg = {
    "deployment": sys.argv[1]
}

#  Public documents 
pub = {
    "rootSrc": (
        "App.vue",
        "main.ts",
        "shims-vue.d.ts"
    ),
    "allRouter": (
        "demo1",
        "demo2",
        "demo3","
    )
}

#  Deployment mode 1  For example, only deploy demo1 application 
demo1 = {
    "router": (
        "index.ts",
        "subImport.js"
        "demo1",
    ),
    "public": (
        "config",
        "index.html",
        "favicon.ico",
    ),
    "rootSrc": (
        "App.vue",
        "main.ts",
        "shims-vue.d.ts"
    ),
    "views": (
        "demo1",
    ),
    "rootFiles": (
        "vue.config.js",
        "yarn.lock",
        "tsconfig.json",
        "package.json",
        "babel.config.js",
        ".prettierrc",
        ".gitignore",
        ".eslintrc.js",
        ".eslintignore",
        ".browserslistrc"
    )
}
 Copy code 

sys.argv[1] Allow to execute python The fixed deployment mode is passed in when the file is . such as :python3 python/index.py demo1

rootSrc Folders are related to src Same level root file , Generally speaking, it will not change , When we have prepared the deployment configuration file , We can start copying files :

python/func.py

#!/usr/bin/python

import os
import shutil

from configs import lsbz
from configs import dy_edz
from configs import basecfg
from configs import pub
import utils

#  To deploy demo1 Application, for example :
def copyConfigs():

    print("views Copy start ")
    os.makedirs("export/src/views")
    for i in os.listdir("./src/views/"):
        if i in demo1['views']:
            os.system('cp -rf ./src/views/'+ i +' export/src/views')
    print("views Copy over ")

    print("public Copy start ")
    os.makedirs("export/public") 
    for i in os.listdir("./public/"):
        if i in demo1['public']:
            os.system('cp -rf ./public/'+ i +' export/public')
    print("public Copy start ")

    print(" Copying root files starts ")
    ls = os.listdir("./")
    for i in ls:
        if i in demo1['rootFiles']:
            shutil.copy('./' + i, "export")
    print(" End of copying root file ")
    
    print("router Copy start ")
        os.makedirs("export/src/router")
        for i in os.listdir("./src/router/"):
            if i in demo1['router']:
                os.system('cp -rf ./src/router/'+ i +' export/src/router')
        for i in pub['allRouter']:
            if i in demo1['router']:
                print(' Ignore ')
            else:
                os.makedirs("export/src/router/" + i)
                    open('export/src/router/' + i + '/index.ts', 'w')
    print("router Copy over ")

    print("layouts Copy start ")
    os.makedirs("export/src/layouts")
    os.system('cp -rf ./src/layouts/* ./export/src/layouts')
    print("layouts Copy over ")

    print("api Copy start ")
    os.makedirs("export/src/api")
    os.system('cp -rf ./src/api/* ./export/src/api')
    print("api Copy over ")

    print("assets Copy start ")
    os.makedirs("export/src/assets")
    os.system('cp -rf ./src/assets/* ./export/src/assets')
    print("assets Copy over ")

    print("components Copy start ")
    os.makedirs("export/src/components")
    os.system('cp -rf ./src/components/* ./export/src/components')
    print("components Copy over ")

    print("hooks Copy start ")
    os.makedirs("export/src/hooks")
    os.system('cp -rf ./src/hooks/* ./export/src/hooks')  
    print("hooks Copy over ")

    print("store Copy start ")
    os.makedirs("export/src/store")
    os.system('cp -rf ./src/store/* ./export/src/store')
    print("store Copy over ")

    print("utils Copy start ")
    os.makedirs("export/src/utils")
    os.system('cp -rf ./src/utils/* ./export/src/utils')
    print("utils Copy over ")        

    print("src Root file copy started ")
    for i in os.listdir("./src/"):
        if i in pub['rootSrc']:
            os.system('cp -rf ./src/'+ i +' export/src')
    print("src End of root file copy ") 
 Copy code 

We know , stay router/subImport.js There is such a string of code in :

//  Full application deployment 
const fullFn = () => {
    return {
        demo1: require('./demo1').demo1, 
        demo2: require('./demo2').demo2,
        demo3: require('./demo3').demo3,
    }
}
 Copy code 

When we only copy demo1 When applied ,router There will only be one folder below demo1, The routes of other sub applications will not be copied in . In this case, the above code will report an error when executing (require('./demo2') The file could not be found )

To solve this problem , We are going to take advantage of configs.py Medium allRouter Add a default folder to all routes in , And there is an empty file index.ts( Now I know why router The name is like this )

print("router Copy start ")
    os.makedirs("export/src/router")
    for i in os.listdir("./src/router/"):
        if i in demo1['router']:
            os.system('cp -rf ./src/router/'+ i +' export/src/router')
    for i in pub['allRouter']:
        if i in demo1['router']:
            print(' Ignore ')
        else:
            os.makedirs("export/src/router/" + i)
            open('export/src/router/' + i + '/index.ts', 'w')
print("router Copy over ")
 Copy code 

When all the documents are ready, we can let python Help us execute a shell Script :

demo1.sh

#!/bin/bash

yarn install
yarn run build

#  Here you can also configure the automatic deployment tool to do the corresponding things , If not , After this file is executed, it will generate dist Folder . Just copy it out manually .
 Copy code 
if basecfg['deployment'] == 'demo1':
    os.chdir('export')
    os.system('sh ./demo1.sh')
 Copy code 

Give Way python Enter into export Folder , Execute the inside demo1.sh file

summary

Open source is not easy , Please quote source for reprint .

copyright notice
author[liuliu6724650],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020723006958.html

Random recommended