How to access environment variables loaded using Vite defineConfig in index.html?

  Kiến thức lập trình

I know that prepending environment variables with VITE_ exposes them to Vite and they become accessible in the index.html file with %VITE_MY_VARIABLE%.

Also, what I understood from the docs is that, it should be possible to load environment variables like this using the Vite config:

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");

  return {
    plugins: [react()],
    define: {
      "process.env.MY_VARIABLE": JSON.stringify(env.MY_VARIABLE),
    },
  };
});

But the problem is, after I do this, MY_VARIABLE is still not accessible in index.html file.

How can I define it in a way that even without the VITE_ prefix it becomes accessible in index.html with %MY_VARIABLE% ?

LEAVE A COMMENT