vue.js打包生成配置文件

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

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

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

//打包时输出可配置文件
const GenerateAssetPlugin = require('generate-asset-webpack-plugin')
const createServerConfig = function (compilation) {
  let cfgJson = {
    ApiUrl: "http://192.168.0.100:3001"
  }
  return JSON.stringify(cfgJson)
}

搜索plugins并添加以下代码

//打包时输入配置
new GenerateAssetPlugin({
  filename: 'serverconfig.json',
  fn: (compilation, cb) => {
    cb(null, createServerConfig(compilation));
  },
  extraFiles: []
}),

第三步:在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)
    });
}

第五步:在app.vue里面调用getConfigJson()获取ApiUrl,使用时直接使用 this.ApiUrl+'/api/‘ 进行调用

//调用getConfigJson()获取ApiUrl
mounted: function() {
  this.getConfigJson();
}

第六步:输入npm run build进行打包,并查看dist文件夹下的serverconfig.json文件,通过修改配置文件实现域名修改

猜你喜欢

转载自www.cnblogs.com/chendongbky/p/9939958.html