vue设置全局配置文件,打包后在dist包内可动态修改配置

6 篇文章 0 订阅

背景:
一样的代码会部署在不同客户方,每次都需要修改不同的接口地址,尤其是公共配置地址多的时候,然后重新打包,感觉很麻烦。写一个公共配置文件,可在打包后手动修改配置文件。

我的项目需要在main.js ,index.html中引入公共配置文件。以下由此情况做说明。一般vue项目按自己需要正常配置就可以。

  1. 首先我的项目静态资源是放在assets中的,一般项目放在static或者public下就可以,在静态资源文件夹下创建一个config.json的文件。
{
    "baseURL": "http://localhost:8080/",
    "onlyoffice": "http://localhost:8082/documents/api.js",
    "iconCssUrl": "http://localhost:8083/css/all.min.css",
}
  1. main.js中使用
import axios from 'axios'

import { createApp } from 'vue'
import App from './App'
import store from '@store'
import router from '@router/index'

const app = createApp(App)
axios.get('/assets/config.json').then(res=>{
 config= res.data
 app.config.globalProperties.$baseURL= config.baseURL
 app.use(router)
    .use(store)
    .use(elementPlusUI)
    .mount('#app')
})

  1. index.html中的使用
<script>
    // 这里用的是原生的请求方式,也可以使用axios
    const xhr = new XMLHttpRequest()
    let config= {}
    xhr.open('GET', '/assets/config.json')
    xhr.send()
    xhr.onload = function() {
        if (xhr.status === 200) {
            config= JSON.parse(xhr.response)
                // onlyoffice地址
            const script = document.createElement('script')
            script.src = config.onlyoffice
            document.head.appendChild(script)
                // css图标文件地址
            const link = document.createElement('link')
            link.setAttribute('rel', 'stylesheet')
            link.setAttribute('type', 'text/css')
            link.setAttribute('href', config.iconCssUrl)
            document.getElementsByTagName('head')[0].appendChild(link)
        }
    }
</script>
  1. 打包后在assets或者static或者public下找到config.json,进行修改,部署后重新刷新浏览器即可更新成功。

参考:vue设置前端配置文件

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值