Vue configures the production environment.env.production, test environment.env.development_ don’t hurry up and collect a wave and watch it slowly

Calm down and watch slowly

First of all, we need to build a project, the
Insert picture description here
dependency package will be downloaded automatically, no need to own npm i

.env will be loaded no matter what environment.
env.production production environment will be
loaded.env.development test development environment will be loaded

Our following examples are written separately and only use .env.production.env.development
Create two new files in the project root directory as .env.production files. The env.development file
Insert picture description here
in the file we configure as follows.
In the .env file

VUE_APP_NAME='vue测试名称'

.env.development file:

NODE_ENV = development  
VUE_APP_URL = 'developmentURL' //自定义变量  必须要以VUE_APP_开头定义

.env.production file:

NODE_ENV = production    
VUE_APP_URL = 'productionURL' //自定义变量  必须要以VUE_APP_开头定义

Next we need to configure package.json

{
    
    
  "name": "my",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    
    
    "serve": "vue-cli-service serve",
    //打包测试开发版本  
    //--mode 后面需要对用文件的名字.env.development  重点是要和.env.后面的名字对应起来
    "build-development": "vue-cli-service build --mode development",
    //打包生产版本
    //--mode 后面需要对用文件的名字.env.production 重点是要和.env.后面的名字对应起来
    "build-production": "vue-cli-service build --mode production",
    "lint": "vue-cli-service lint"
  },
  ...//json文件太长 后面的没用复制过来  主要看上面的scripts
}

Next, we print the VUE_APP_URL we set in app.vue

  mounted() {
    
    
    console.log(process.env,'process.env')
    console.log(process.env.VUE_APP_URL, "VUE_APP_URL");
  }

If we run
npm run serve locally, we
will load the two files .env and .env.development.
We will see the console print and we
Insert picture description here
can see that process.env is a global object. We can add the properties we need to the object and
run npm run When serve, it will automatically compile and test the development version, so we can add variables to the .env.development file.
We try to package the production version

npm run build-production    

The dist folder will be generated in the root directory of the file

We try to open dist locally and run the vue packaged file

We need to install the http-server npm package globally

npm i -g http-server

We go into the dist folder and open cmd to
execute http-server
Insert picture description here

Open in the browser to see the console print
Insert picture description here

It is indeed the variable we printed under app.vue, and the value is the value we set in .env and .env.production;
this greatly facilitates our packaging process, without the need to package test URLs and production URLs back and forth every time Switched~
We can encapsulate this VUE_APP_URL into axios to make our development more convenient~

Guess you like

Origin blog.csdn.net/qq_43291759/article/details/115344737