美文网首页
2019-05-29 vue 打包时生成配置文件

2019-05-29 vue 打包时生成配置文件

作者: c6e71129966d | 来源:发表于2019-05-29 10:50 被阅读0次

vue 代码打包完上传到服务器,需要更换域名,那么此时需要一个配置文件,直接在配置文件配置域名或者需要的改变的字段什么的。

安装插件 generate-asset-webpack-plugin

命令行:npm install --save-dev generate-asset-webpack-plugin

配置 webpack.prod.config.js 文件

var GenerateAssetPlugin = require('generate-asset-webpack-plugin');

const createServerConfig = function (compilation) {

  let cfgJson = { ApiUrl: ' http://192.168.**.**:8080/mdap/ ' };

  return JSON.stringify(cfgJson);

}

在plugins:[]中 里边配置 

// 让打包的时候输入可配置的文件

new GenerateAssetPlugin({

        filename: 'serverconfig.json',

        fn: (compilation, cb) => {

            cb(null, createServerConfig(compilation));

        },

        extraFiles: []

    })

进行打包  npm run build

打包文件 dist 里包含 serverconfig.json 

在main.js获取ApiUrl

Vue.prototype.getConfigJson = function () {

  if (sessionStorage.getItem('ApiUrl')) {

    Vue.prototype.ApiUrl = sessionStorage.getItem('ApiUrl');

  } else {

    this.$http.get("serverconfig.json").then(function (result) {

      sessionStorage.setItem('ApiUrl', result.body.ApiUrl);

      Vue.prototype.ApiUrl = result.body.ApiUrl;

    }).catch((error) => { console.log(error) });

  }

}

相关文章

网友评论

      本文标题:2019-05-29 vue 打包时生成配置文件

      本文链接:https://www.haomeiwen.com/subject/noketctx.html