SoFunction
Updated on 2025-03-10

Methods of using webpack to dynamically configure and package multiple environment domain names in vue project

Nowadays, front-end separation and various frameworks are prevalent, the packaging requirements for projects are becoming more and more complex. I share a method of entering different commands according to the command line in a vue project to package different environment domain names. (Replies are welcome, thank you.)

1. Install the plug-incross-env,npm install cross-env --save -dev, used to configure command line input.

2. Modify the script command:

Three environments are configured: test (test), ready (pre-release), and prod (formal). npm run build is set to npm run build:prod by default. You can also configure more commands and customize parameters according to your own needs. I saw someone modifying the default parameter NODE_ENV on the Internet. There are many places in the configuration file that reference this parameter. I think this default parameter can be changed, just add a parameter to yourself (add a BUILD_ENV parameter here).

"scripts": {
  "dev": "webpack-dev-server --inline --progress --config build/",
  "start": "npm run dev",
  "unit": "jest --config test/unit/ --coverage",
  "e2e": "node test/e2e/",
  "test": "npm run unit && npm run e2e",
  "build": "npm run build:prod",
  "build:test": "cross-env NODE_ENV=production BUILD_ENV=test node build/",
  "build:ready": "cross-env NODE_ENV=production BUILD_ENV=ready node build/",
  "build:prod": "cross-env NODE_ENV=production BUILD_ENV=prod node build/"
 },

3. Modify the config directory

The default configuration inside is as follows: There is only one NODE_ENV

'use strict'
 = {
 NODE_ENV: '"production"', 
}

Modified configuration:

'use strict'
const BUILD_ENV = .BUILD_ENV
let baseUrl 
switch (BUILD_ENV) {
 case 'test':
  baseUrl = ''
  break; 
 case 'ready':
  baseUrl = ''
 break;
 case 'prod':
  baseUrl = ''
 break;
}
 = {
 NODE_ENV: '"production"', 
 BUILD_ENV: '"' + BUILD_ENV + '"',
 baseUrl: '"' + baseUrl + '"',
}

The modified configuration has added two attributes BUILD_ENV and baseUrl. Remember to splice the attribute value in double quotes. .BUILD_ENV is the value of BUILD_ENV entered in the command line, and then according toBUILD_ENVMake corresponding judgments. In the project, you can passGet the three exposed attributes. For example, interface files need to dynamically modify different environment domain names.

Summarize

The above is the method of using webpack dynamic configuration to package multiple environmental domain names in the vue project introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!