vue 部署后修改配置文件(接口IP)

发布于:2024-03-02 ⋅ 阅读:(92) ⋅ 点赞:(0)

近期,有一个项目,运维在部署的时候,接口ip还没有确定,而且ip后面的路径一直有变动,导致我这里一天打包至少四五次才行,很麻烦,然后看了下有没有打包后修改配置文件修改接口ip的方法,对比了下,使用以下方法

前提:vue2

方案一:

    在public文件夹新建config.js文件

#config.js
window.config= {
  ServeUrl:"xx",
  FileUrl:"xx",
}

   main.js 中配置

 axios.defaults.baseURL = window.config.ServeUrl;

因为此方案灵活性不好,没有测试使用 

方案二(我使用的)

  

   下载generate-asset-webpack-plugin插件 

    本地的配置文件模板config.js(根目录创建)

module.exports = {
  ServeUrl:"xxx",
}

    vue.config.js配置:

const GenerateAssetPlugin = require('generate-asset-webpack-plugin')
const configs = require('./config')  //引用本地的配置文件
 // 导出配置文件的内容
var createServerConfig = function(compilation) {
  return JSON.stringify(
    Object.assign(
      {
        _hash: compilation.hash,
      },
      configs
    )
  )
}
module.exports = {
  publicPath: process.env.VUE_APP_publicPath, 
  lintOnSave: false,
  productionSourceMap: false, //打包不生成map
  // devServer: {
  //   open: true,
  //   proxy: 'http://localhost:8080'
  // }
  chainWebpack(config) {
    config.plugin('html').tap((args) => {
      args[0].title = process.env.VUE_APP_Title
      return args
    })
    // 打包生成配置文件
    config.plugin('GenerateAssetPlugin').use('generate-asset-webpack-plugin', [
      {
        filename: 'config.json',//生成的文件
        fn: (compilation, cb) => {
          cb(null, createServerConfig(compilation))
        },
        extraFiles: [],
      },
    ])
  }
}

   本地不同环境打包使用的配置环境

        具体设置看vue .env配置环境变量-CSDN博客

   

NODE_ENV='test'
VUE_APP_publicPath='/eseal/policy'

VUE_APP_ServeUrl="x"
VUE_APP_FileUrl="x"

package.json配置

     为了本地环境和线上环境做区分,需要修改默认启动配置

"serve": "vue-cli-service serve --mode test",

main.js配置

if(process.env.NODE_ENV !== 'test'){    //前提是本地运行环境是test
  axios({
    method: 'get',
    url: process.env.VUE_APP_publicPath+'/config.json',  //文件存放地址
  }).then(res=>{
    console.log('读取配置',res);
    axios.defaults.baseURL = res.data.ServeUrl;
    Vue.prototype.$ServeUr = res.data.ServeUr
    Vue.prototype.$FileUrl = res.data.FileUrl
  })
}else{
axios.defaults.baseURL= process.env.VUE_APP_ServeUrl
Vue.prototype.$ServeUr = process.env.VUE_APP_ServeUr
Vue.prototype.$FileUrl = process.env.VUE_APP_FileUrl
}

axios.js 接口请求文件配置

    因为使用全局变量的this获取不到数据,引入vue也不行,就多写了一次,根据不同需求,这个也可以不写的

if(process.env.NODE_ENV !== 'test'){
  axios({
    method: 'get',
    url: process.env.VUE_APP_publicPath+'/config.json',
  }).then(res=>{
    console.log('读取配置',res);
    axios.defaults.baseURL = res.data.ServeUrl;
  })
}else{
axios.defaults.baseURL= process.env.VUE_APP_ServeUrl
}

 修改配置之后,刷新一下页面即可获取最新的数据

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到