vite项目配置:后端希望能任意更改打包后的接口请求地址
·
需求
有这样一个需求:项目线上的接口地址是经常会变化的,后端希望接口地址放在一个配置文件如config.js中,这个文件不能被打包压缩,从而后端能任意修改接口地址,这样就不用让前端重新打包了
个人实践,总结了两种方案:
方案一
index.html
新增script标签,window对象上挂载请求路径,后端想修改接口地址在html中修改即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
// 新增,放在上面,避免js执行顺序问题
<script>
window.httpurl = "http://192.168.1.236:10007/"
</script>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
axios
设置请求路径为window.httpurl
const instance = axios.create({
...
baseURL: window.httpurl
})
方案二
index.html
新增<script src="./config.js"></script>,放在上面,避免js执行顺序问题,vite只会打包type="module"的script标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
// 新增
<script src="./config.js"></script>
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
config.js
新建config.js,直接放在public目录下,内容如下
window.httpurl = "http://192.168.1.236:10007/"
axios
设置请求路径为window.httpurl
const instance = axios.create({
...
baseURL: window.httpurl
})
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)