1.引入webpack 插件
npm install generate-asset-webpack-plugin --save-dev
2.在vue.config.js 中引入插件
const GenerateAssetPlugin = require('generate-asset-webpack-plugin')
3.createServerConfig 中 存放要打包隔离的文件
var createServerConfig = function(compilation){
let cfgJson={ApiUrl:"http://www.adoctors.cn"};
return JSON.stringify(cfgJson);
}
4.vue.config.js中configurewebpack对象下引入generate-asset-webpack-plugin插件,此时build:prod 已经能看到serverconfig.json 文件
plugins:[new GenerateAssetPlugin({
filename: 'serverconfig.json',
fn: (compilation, cb) => {
cb(null, createServerConfig(compilation));
},
extraFiles: []
})]
5.在项目入口处获取json文件的内容,并存入全局,(sessionStorage),接口的beseurl 获取相应需要的地址即可
Vue.prototype.getConfigJson=function(){
this.$http.get("serverconfig.json").then((result)=>{
//用一个全局字段保存ApiUrl 也可以用sessionStorage存储
Vue.prototype.ApiUrl=result.body.ApiUrl;
}).catch((error)=>{console.log(error)});
}