Uniapp’s own configuration only distinguishes between production (NODE_ENV= production) and non-production (NODE_ENV=development) environments, which are built into Uniapp to distinguish behavior. For example, when the applets use different environment variables, the corresponding dev or build directory will be generated under the dist folder. However, in actual development and deployment, multiple sets of environment API configurations need to be differentiated.
1. Use the CLI to build the UniApp project
Uniapp offers two ways to create projects:
1. Create a vm using the HbuilderX editor
2. Create a vm using the vue-CLI
The first method can only be developed through Hbuilderx, run and release with no exposed configuration files, and the only way to distinguish multiple environments is to manually switch variables to load different apis. In the second way, we can use vscode YYds, which is our own convenient editor. As long as we modify the configuration of WebPack and use different running packaging commands, we can distinguish the corresponding environment configuration and facilitate Jenkins’ automatic packaging deployment.
As shown in the figure, after creating the project through clipackage.json
There are corresponding run and package commands in the file:Note that in the commandNODE_ENV
Variables are not modifiable. As mentioned above, they are built-in to UniApp. You can create other variables to distinguish between environments.
2. Create an environment file
If you need to distinguish the development test environment, UAT environment, and production environment, you need to create an environment file named.env in the root directory. The environment of
.env.dev
VUE_APP_ENV='dev' VUE_APP_BASE_API =' https://dev.com'Copy the code
.env.uat
VUE_APP_ENV='uat' VUE_APP_BASE_API =' https://uat.com'Copy the code
.env.pro
VUE_APP_ENV='pro' VUE_APP_BASE_API =' https://pro.com'Copy the code
3. Modify the package. Json
For example, in the H5 environment, add the –mode XXX parameter to the command of each environment. The name corresponds to the environment file to be created
Modify before:
Revised:
"scripts": {
"dev:h5-dev": "cross-env NODE_ENV=development UNI_PLATFORM=h5 vue-cli-service uni-serve --mode dev",
"dev:h5-uat": "cross-env NODE_ENV=development UNI_PLATFORM=h5 vue-cli-service uni-serve --mode uat",
"dev:h5-pro": "cross-env NODE_ENV=development UNI_PLATFORM=h5 vue-cli-service uni-serve --mode pro",
"build:h5-dev": "cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-build --mode dev",
"build:h5-uat": "cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-build --mode uat",
"build:h5-pro": "cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-build --mode pro"
},
Copy the code
In this case, run the corresponding command, print process.env, and find that variables in different environment files are loaded successfully
npm run dev:h5-dev/yarn dev:h5-dev
npm run build:h5-pro/yarn build:h5-pro