背景:
一样的代码会部署在不同客户方,每次都需要修改不同的接口地址,尤其是公共配置地址多的时候,然后重新打包,感觉很麻烦。写一个公共配置文件,可在打包后手动修改配置文件。
我的项目需要在main.js ,index.html中引入公共配置文件。以下由此情况做说明。一般vue项目按自己需要正常配置就可以。
- 首先我的项目静态资源是放在assets中的,一般项目放在static或者public下就可以,在静态资源文件夹下创建一个config.json的文件。
{
"baseURL": "http://localhost:8080/",
"onlyoffice": "http://localhost:8082/documents/api.js",
"iconCssUrl": "http://localhost:8083/css/all.min.css",
}
- 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')
})
- 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>
- 打包后在assets或者static或者public下找到config.json,进行修改,部署后重新刷新浏览器即可更新成功。
参考:vue设置前端配置文件