You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte.js(Vite)中如何在index.html中使用环境变量

在Vite项目的index.html中正确使用环境变量的方法

你在index.html里使用import.meta.env.VITE_KAKAO_API的方式是错误的,因为import.meta.env语法仅适用于JS/TS模块文件,在index.html中需要使用Vite专门提供的环境变量插值格式。

正确写法

将script标签的src属性修改为%VITE_KAKAO_API%:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- 正确的环境变量引用方式 -->
    <script
      async
      type="text/javascript"
      src="%VITE_KAKAO_API%"
    ></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

额外注意事项

  • 确保你的.env文件中变量确实以VITE_开头,例如:
    VITE_KAKAO_API=https://dapi.kakao.com/v2/maps/sdk.js?appkey=your_app_key
    
  • 修改.env文件后,需要重启Vite开发服务器,否则新的环境变量不会生效
  • 生产构建时,Vite会自动将这些%VITE_XXX%占位符替换为实际的环境变量值

内容的提问来源于stack exchange,提问作者Jay0813

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:50:28