vue 项目打包的过程中通过命令行修改 api 接口前缀

6 篇文章 0 订阅

环境:vue 全家桶、nodeJs、chrome浏览器

需求:后端需要将 npm run build 之后的文件部署到不同的服务器上去,后端希望在 npm run build 命令的后面直接加上 api = https://192.168.166.156:8444 (举个例子) ,在命令行执行之后整个页面的 api 接口前缀就会改为https://192.168.166.156:8444

实现原理:

1. 在 webpack.prod.conf.js 中使用( webpack plugin ) GenerateAssetPlugin 插件在打包的时候输出可配置文件 serverConfig.json

// build 之后更改接口地址
//让打包的时候输出可配置的文件
var GenerateAssetPlugin = require("generate-asset-webpack-plugin");
var createServerConfig = function(compilation) {
  let cfgJson = { ApiUrl: process.argv[2] };
  return JSON.stringify(cfgJson);
};
// 放在 plugins 配置项下
// 打包的时候输出文件配置
    new GenerateAssetPlugin({
      filename: "serverConfig.json",
      fn: (compilation, cb) => {
        cb(null, createServerConfig(compilation));
      },
      extraFiles: []
    })

2. 在 Login.vue/main.js 里使用 axios 请求该配置文件中的 ApiUrl 参数并存储在 localStorage 

getHosts: function() {
      let _self = this;
      this.$ajax
        .get("serverConfig.json")
        .then(result => {
          // localStorage 分别存储 host、ip、port (业务需要)
          let ip = result.data.ApiUrl.split(":")[1].split("/")[2]; // 192.168.166.156
          let host = result.data.ApiUrl.split(":")[0]; // 8444 点击打开链接
          let port = result.data.ApiUrl.split(":")[2]; // https
          _self.$store.set(  // $store 为全局注册的 store 插件,管理 localStorage
            "presetIP",
            ip
          );
          _self.$store.set("presetHost", host);
          _self.$store.set("presetPort", port);
          _self.setHistoryIP();
        })
        .catch(error => {
          console.log(error);
        });
    }

3. 在 api 接口配置 js 中取出存储在 localStorage 中的 host、ip、port 字段组合成接口前缀

 

注意:在本地测试是否能跑通需要使用 nodeJs 的 http-server 插件开启本地服务器

或者浏览 vue 项目打包通过命令修改 vue-router 模式,修改 API 接口前缀 查看另一种方式

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值