1. 程式人生 > >vue.js打包生成配置檔案

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檔案,通過修改配置檔案實現域名修改