javascriptvuejs3vite

How can I use Vite env variables in vite.config.js?


With the following .env in my Vite project:

# To prevent accidentally leaking env variables to the client, only
# variables prefixed with VITE_ are exposed to your Vite-processed code

VITE_NAME=Wheatgrass
VITE_PORT=8080

How can I use VITE_PORT in my vite.config.js?


Solution

  • You can load the app level env variables and add them to the Node level env variables:

    import { defineConfig, loadEnv } from 'vite';
    import vue from '@vitejs/plugin-vue';
    
    
    export default ({ mode }) => {
        process.env = {...process.env, ...loadEnv(mode, process.cwd())};
    
        // import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
        // import.meta.env.VITE_PORT available here with: process.env.VITE_PORT
    
        return defineConfig({
            plugins: [vue()],
    
            server: {
                port: parseInt(process.env.VITE_PORT),
            },
        });
    }