vue-cli3/4关于process.env的配置


由于我们的项目需要在不同环境下进行运行(开发,生产,测试等),设置process.env这避免我们需要多次的去切换请求的地址以及相关的配置。

默认的有development和production两种,分别对应运行运行vue-cli-service serve与vue-cli-service build两种环境。也就是说开发环境默认为development,打包之后的环境默认为production。同时也支持不同环境不同配置,在项目根目录中配置.env.development与.env.production两个文件(使用方法与.env一致),系统根据不同环境获取不同配置文件。达到不同环境不同配置的效果。
然而实际开发中,我们不一定只有两个环境,所以vue-cli也提供了多环境的配置方法。在系统根目录中配置.env.[environmentName]文件,然后运行时候加上–mode environmentName就可以将配置文件切换到对应文件中去

 一 建立.env系列文件

首先我们在根目录新建3个文件,分别为.env.development,.env.production,.env.test

  • env.development 模式用于serve,开发环境,就是开始环境的时候会引用这个文件里面的配置
  • .env.production模式用于build,线上环境
  • .env.test 测试环境

二  修改.env系列文件

.env.development

VUE_APP_BASE_API = 'http://localhost:8091/api/'

.env.production

VUE_APP_BASE_API = 'http://jstudio.org/api/'

.env.test

VUE_APP_BASE_API = 'http://192.169.123:8092/api/'

四 更改package.json文件 

  "scripts": {
    "dev": "vue-cli-service serve",
    "test": "vue-cli-service serve --mode test",
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:test": "vue-cli-service build --mode test",
    "lint": "vue-cli-service lint"
  }

五 使用

当需要用到该变量是可以用process.env.VUE_APP_BASE_API进行取值。

例如在js文件中直接使用

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000,
})

1.Vue2.0页面写法

在data中使用



在computed() 中使用



2. Vue3.0页面写法

在setup()引用



在computed()中使用



svn