How to use process.env in Vite

whchi - Apr 6 '23 - - Dev Community

The process object is a global object that is exclusive to the Node.js environment, and therefore cannot be accessed in a browser environment.

However, bundlers like webpack and vite can handle this limitation by processing the custom process variable before rendering it for browser use.

To achieve this, vite uses 2 libraries:

  1. vite-plugin-env-compatible: load env file
  2. @rollup/plugin-replace: replace javascript variables into env file's variables

The official documentation states that all VITE_* environment variables set in the .env file can be accessed through import.meta.env.*, e.g: VITE_MY_VAR="abc" can be use as import.meta.env.VITE_MY_VAR.

However, it's not recommended for users to define environment variables with the VITE_* prefix when developing packages.

To enable greater flexibility in usage, it's recommended to convert environment variables to the form of process.env.

The following example shows an actual implementation.

  • .env
YOUR_STRING_VARIABLE="helloworld"
YOUR_BOOLEAN_VARIABLE=false
Enter fullscreen mode Exit fullscreen mode
  • vite.config.js
import { defineConfig, loadEnv } from 'vite';

export default defineConfig(({ command, mode }) => {
    const env = loadEnv(mode, process.cwd(), '');
    return {
        define: {
            'process.env.YOUR_STRING_VARIABLE': JSON.stringify(env.YOUR_STRING_VARIABLE),
            'process.env.YOUR_BOOLEAN_VARIABLE': env.YOUR_BOOLEAN_VARIABLE,
            // If you want to exposes all env variables, which is not recommended
            // 'process.env': env
        },
    };
});
Enter fullscreen mode Exit fullscreen mode

then you can use process.env.YOUR_ENV in anywhere of your project.

. . . . . . . . . . . . . . . . . .
Terabox Video Player