The problem background

In both scenarios, different interface urls and external referenced urls in the front-end code of STG and PROD environment need to be extracted into static variables, and the access interface of the website can be changed by changing the configuration URL of static variables

Scenario 1: When making docker automatic deployment platform, when the server address changes, the back-end interface migrates, and the front end needs to be automatically deployed on the platform instead of manually deployed, a configuration file needs to be edited and changed online.

Scenario 2: The front end is generated by engineering, but the front and back ends are not deployed separately. When the backend is deployed through automation, it needs to go through the code acquisition — common compilation — STG deployment —- PRD deployment step, and the backend deployment of STG is generated by the front end OF the STG code. Prod is proD code. In order to deploy on the upper platform, shell scripts need to be written on the back end to distinguish between STG and PROD environment, and then different front-end packages are placed in the root directory of the server at different stages. Because it is a static resource package of the whole project, it may be relatively large, so it needs to be zip compressed and then decompressed. The back end asks if you can just pull out different parts of different environments and just move this one file around to dramatically speed up deployment.

The solution

To sum up: find two ways to solve the problem

  1. Method 1: The front end puts the configurations of different environments into a config.js file, and then distinguishes online or test environments by different urls accessed by users. Each time the server changes, you only need to change this configuration file to distinguish between the urls accessed by different environments
  • First, create config.js configuration file under vuecli2 is static and vueCli3 is public, including different interface addresses corresponding to keys in different environments
// Create a new config.js file in the public directory
export consst config=[
  // Interface address
  targetAddress: {
    local:"http://xxx.xxx.local.com".stg: "http://xxx.xxx.stg.com".prod:'http://xxx.xxx.prod.com',},urlMap: {
	local: ['10.118.120.41:8080'.'localhost:8080'.'10.118.120.43:8089'].stg: ['XXX.XXX.stg.com'].prod: ['XXX.XX.prod.com'].cas: {
      local:"http://XXX.XXX.local/cas/#/".stg: "http://XXX.XXX.stg/cas/#/".prod:'http://XXX.XXX.prod/cas/#/',}},developerUrl: {
    local:"http://XXX.XXX.local/subiectallmanage/".stg: "http://XXX.XXX.stg/subiectallmanage".prod:'http://XXX.XXX.prod/subiectallmanage',}]Copy the code
  • Then introduce the config configuration file into the API interface file of the project, and determine the environment (local, STG or PROD) according to the address entered by the user, and then extract the URL address in the corresponding Config according to the environment
 // Write the following code under API /api.js in the interface file
 import { config } from '.. /.. /public/js/config.js'
 let targetUrl = ' '; // The Url of the back-end interface
 const curUrl = window.location.href; // The url entered by the user
 const map = config.urlMap;
 for (let env in map) {
	if( env ! ='cas') {
		let hasUrl = map[env].some(e= > {
			return curUrl.includes(e);
		})
		if(hasUrl) { targetUrl = config.targetAddress[env]; }}}Copy the code
  1. Method 2: Use the plug-in generate-asset-webpack-plugin to generate a JSON file at package time and then request the configuration in JSON via AXIOS. Because the back end can distinguish between production and test environments, you only need to have a default JSON file and a production JSON test JSON. The back end then uses shell scripts to determine the current environment to replace the production JSON to the default JSON directory.
  • Install the plugin generate-asset-webpack-plugin
npm i generate-asset-webpack-plugin -D
Copy the code
  • Add a plug-in to vue.config.js and use the plug-in to generate json files
var GenerateAssetPlugin = require('generate-asset-webpack-plugin');
var createServerConfig = function(compilation) {
    // Configure the required API interface
    let cfgJson = {
        VUE_APP_SERVE_URL: process.env.VUE_APP_PULIC_PATH,
        VUE_APP_PULIC_ACTIVE: process.env.VUE_APP_PULIC_ACTIVE
    }
    return JSON.stringify(cfgJson);
}
    module.exports = {
        configureWebpack: {
            plugins: [
                new GenerateAssetPlugin({
                    // Different environments generate different JSON files stgconfig. json prdconfig. json
                    filename: `${process.env.VUE_APP_STATUS}Config.json`.fn: function(compilation, cb) {
                        cb(null, createConfig(compilation))
                    }
                })
            ]
        }
    }
Copy the code
  • After the configuration is complete, run NPM run test to generate the test package and generate the stgconfig. json file in the test directory, as shown in the following figure

  • Then rename the generated stgconfig. json file serverconfig.json to public and create a new getConfigurl.js file in the SRC directory
import axios from 'axios';
Vue.prototype.getConfigJson = function() {
        axios.get("serverconfig.json").then((result) = > {
            // Mount it to the vue prototype so it can be called in the project
            Vue.prototype.$configApiUrl = result.data;
            console.log(result.data);
        }).catch((error) = > {
            console.log('getConfigJson Error! ', error)
        })
    }
Copy the code
  • Finally, it will be used in the project
Process. The env. VUE_APP_SERVE_URL substitutethis. $configApiUrl. VUE_APP_SERVE_URL process. The env. VUE_APP_PULIC_ACTIVE replacementthis.$configApiUrl.VUE_APP_PULIC_ACTIVE
Copy the code

Then execute the NPM run build package to generate prdconfig. json and send both configuration files to the back end.