vue2设置运行环境和打包环境变量

环境

 env —— 所有模式共用
.env.local —— 所有模式共用,但不会被 git 提交,自动添加到.gitignore
.env.development —— 仅开发模式使用,使用npm run server时默认会加载此配置文件
.env.developmen.local—— 仅开发模式使用,但会被 git 忽略自动添加到.gitignore,使用npm run server时默认会加载此配置文件
.env.production —— 仅生产模式使用,使用npm run build时默认会加载此配置文件
.env.staging—— 仅staging模式使用,使用需要配置–mode staging

.env.dev
.env.test
.env.prod

编写配置内容

# 运行环境
NODE_ENV="development"
  
# 设置Axios 基础路径
VUE_APP_BASE_URL = "/api/"

# 设置App运行路径
VUE_APP_MAPP_URL ="https://t.m.xxxx.com" 

# 是否使用Hash路由
VUE_APP_MAPP_URL = 'true'
想要运行环境来设置的话 就可以在这里设置 但是有1点需要注意  这里的前缀必须是VUE_APP_开头
其他的识别不到

在package.json文件中编写启动命令

这里的 env 文件是会默认加载 其他的都需要手动在这里添加启动命令

"scripts": {
    "dev": "node --max_old_space_size=4096 node_modules/@vue/cli-service/bin/vue-cli-service.js serve --mode dev",
    "test": "node --max_old_space_size=4096 node_modules/@vue/cli-service/bin/vue-cli-service.js serve --mode test",
    "prod": "node --max_old_space_size=4096 node_modules/@vue/cli-service/bin/vue-cli-service.js serve --mode prod",
    "build:dev": "vue-cli-service build --mode dev",
    "build:test": "vue-cli-service build --mode test",
    "build:prod": "vue-cli-service build --mode prod",
  }

使用环境变量

启动后 可以随意页面调用配置运行环境里面的  process.env.xxx   

示例 vue2 

vue2 使用的是webpack 和vue3使用vite写法不一样哦!!!

const { defineConfig } = require("@vue/cli-service");
const { getProxyConfig } = require('./src/config/proxy');

module.exports = defineConfig({
  publicPath: "/",
  transpileDependencies: true,
  outputDir: "./dist",//打包路径
  devServer: {
    port: 10001,
    proxy: getProxyConfig(process.env.NODE_ENV)//这里传入env运行环境去动态设置proxy
  }
});
function getProxyConfig (env) {
  const urlConfig = {
    '/api': {
      'development': 'http://xxx:10000/api/',
      'test': 'https://xxx/api',
      'production': 'https://xxx/api',
    },
    '/pay': {
      'development': 'http://xxx:10000/pay',
      'test': 'http:/xxx/pay',
      'production': 'https://xxx.com',
    }
  }

  const target = (targetTag, baseUrl) => ({
    target: targetTag,
    changeOrigin: true,
    pathRewrite: {
      [`^${baseUrl}`]: '/',
    },
  });

  return Object.entries(urlConfig).reduce((result, [key, value]) => {
    result[key] = target(value[env], key);
    return result;
  }, {}); 
}

module.exports = { getProxyConfig };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

家里有只小肥猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值