0

How to use environment variable in index.html? I tried like this

index.html
<!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" />
    // error is occured
    <script
      async
      type="text/javascript"
      src="{import.meta.env.VITE_KAKAO_API}"
    ></script>

  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

Also added .env file in root and create variable with prefix(VITE_)

Jay0813
  • 39
  • 4
  • 1
    The `index.html` file is not a script file that is interpreted as a template like that. You can try loading this script dynamically from a JS file, there the env will work. – Marcos Sandrini Nov 24 '22 at 08:24

1 Answers1

0

In case of a one time replacement within the app.html file, In all cases, you want to look at this post: String replacements in index.html in vite. It replaces a string at build time with a vite plugin. If your env var changes, you need to trigger a new build.

In a case of a dynamic property (let's say the locale of your website), you need to have a server (not a static site) and use the hooks where you can read your env variables (doc on hooks: https://kit.svelte.dev/docs/hooks):

export const handle = async ({ event, resolve }) => {
    return await resolve(event, { transformPageChunk: ({ html }) => html.replace('%lang%', lang) });
};
Ennoriel
  • 144
  • 1
  • 8