iview-admin配置外放

因为项目需求,需要在打包之后能更改文件配置接口

1.安装插件

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

2.使用插件(vue.config.js)

vue-cli3中webpack的打包配置都放在根目录下vue.config.js中哦,vue-cli2放在build目录下。

1)引入plugin
const GenerateAssetPlugin = require('generate-asset-webpack-plugin');
2)定义需要生成的配置内容,配置项在cfgJson对象中定义,该函数在plugin中用到
var createServerConfig = function(compilation){
     // 配置需要的api接口
     let cfgJson = {
     VUE_APP_SERVE_URL: 'http://172.16.88.88:60232',
     //静态图片地址
     VUE_APP_UPLOADFILE_URL: 'http://172.16.88.88:60232'
  }
  return JSON.stringify(cfgJson);
}
3)在module.exports中调用plugin:在module.exports中增加属性configureWebpack,configureWebpack的plugins中调用plugin(其他plugin也可以在这里引入,与vue-cli2方法一致)
module.exports = {
  configureWebpack: {
    plugins: [
      new GenerateAssetPlugin({
        filename: 'dynamicConfig.json',
        fn: (compilation, cb){
          cb(null, createConfig(compilation))
        }
      })
    ]
  }
}

3.在main.js请求所创建的文件并且本地存储

import axios from 'axios';
// 应用配置文件里面的接口数据
 Vue.prototype.getConfigJson = function () {
     axios.get("serverconfig.json").then((res) => {
     localStorage.setItem("apiUrl", res.data.VUE_APP_SERVE_URL) //接口地址
     localStorage.setItem("apiImage", res.data.VUE_APP_UPLOADFILE_URL) //静态资源地址
     }).catch((error) => {
     console.log('未获取到接口地址', error)
 })
}

4.app.vue调用

 mounted() {
   this.getConfigJson()
 },

5.config内使用

 baseUrl: {
     dev: localStorage.getItem("apiUrl"),
     pro: localStorage.getItem("apiUrl")
 },
 
 defaultImageUrl: localStorage.getItem("apiImage"),
 

image.png

image.png

评论

暂无评论