Vue中配置开发环境变量

222 阅读1分钟

Vue中配置开发环境变量

首先在vue项目根目录与src文件同级

.env.production 生产环境变量
.env.development 开发环境变量
直接创建这两个文件即可
在文件中定义变量复值为参数例如:

# 开发环境
port=9999
VUE_APP_BASE_URL="https://www.thenewstep.cn/v1/vue3system/api"
VUE_APP_BASE_API="/api"

image.png

配置完成后如何使用?下面利用解决跨域代码举例:

const { defineConfig } = require('@vue/cli-service')
const port = process.env.port || process.env.dev_port || 8888
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    port: port,
    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        // target: 'https://www.thenewstep.cn/v1/vue3system/api',
        target: process.env.VUE_APP_BASE_URL,
        changOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ""
        }
      }
    }
  }
})

image.png

配置完成需要重启项目才会执行

执行完成,这就是通过变量作为值去使用配置同源策略一个用法。

image.png

在定义环境变量时候,注意不要留逗号等等,会导致项目无法启动。

image.png