需求

有这样一个需求:项目线上的接口地址是经常会变化的,后端希望接口地址放在一个配置文件如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  
})
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐