zoukankan      html  css  js  c++  java
  • vue打包之后生成一个配置文件修改请求接口

    问题描述:

    在npm run build 生成dist后,url配置也被固定了,传到运行的前端服务器上后,假设某次,api服务器的ip修改了,改动只是更新下这个url,但是却需要回到前端源码,修改url后,在重新npm run build,然后再把整个dist再重新传到前端服务器。

    解决方案:

    第一步:安装generate-asset-webpack-plugin插件

    npm install --save-dev generate-asset-webpack-plugin
    

    第二步:配置webpack.prod.conf.js文件

    //让打包的时候输出可配置的文件
    var GenerateAssetPlugin = require('generate-asset-webpack-plugin'); 
    var createServerConfig = function(compilation){
      let cfgJson={ApiUrl:"http://www.adoctors.cn"};
      return JSON.stringify(cfgJson);
    }
    
    //让打包的时候输入可配置的文件
    //这段代码加在plugins:[]中
        new GenerateAssetPlugin({
            filename: 'serverconfig.json',
            fn: (compilation, cb) => {
                cb(null, createServerConfig(compilation));
            },
            extraFiles: []
        })
    

    第三步:输入npm run build打包代码 结果如下

    第四步:以后需要修改域名之类的 在serverconfig.json修改即可

    第五步:获取ApiUrl

    //在main.js中定义一个全局函数
    Vue.prototype.getConfigJson=function(){
        this.$http.get("serverconfig.json").then((result)=>{
            //用一个全局字段保存ApiUrl  也可以用sessionStorage存储
            Vue.prototype.ApiUrl=result.body.ApiUrl;
        }).catch((error)=>{console.log(error)});
    } 
    
    

    第六步:使用ApiUrl

    //在app.vue里面  执行this.getConfigJson();
    mounted:function(){
          this.getConfigJson();
    }
    
    //之后...用在需要用到的地方  因为ApiUrl已经是全局了 可以直接用this.ApiUrl
    var url=this.ApiUrl+'/api/....'
    
  • 相关阅读:
    常用字段类型
    触发事件中的sender
    $符号基本用法$() ${} $(())
    expect语法
    apt 和 apt-get的区别
    python字符串中 r'', b'', u'', f'' 的含义
    linux正则表达式
    Linux下apt-get命令详解(安装、卸载、更新、查询软件包)
    创建linux service服务
    Ubuntu下deb包的解包、打包
  • 原文地址:https://www.cnblogs.com/adoctors/p/8472802.html
Copyright © 2011-2022 走看看