Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vuejs3

vite

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?

like image 713
Matt Deacalion Avatar asked Feb 26 '21 16:02

Matt Deacalion


People also ask

Can I use variables in .env file?

You can set default values for environment variables using a .env file, which Compose automatically looks for in project directory (parent folder of your Compose file). Values set in the shell environment override those set in the .env file.

How do I import a .env variable?

On the Projects page, select the project that you want to import environment variables to, and click Properties to open the Project Properties window. On the General page, click Environment. In the Environment Variables dialog, click Import from File.

Is .env a config file?

In case you are still wondering what all this means, well, you are probably new to the . env file. It's actually a simple configuration text file that is used to define some variables you want to pass into your application's environment.


1 Answers

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: process.env.VITE_PORT,
        },
    });
}
like image 150
Matt Deacalion Avatar answered Sep 19 '22 08:09

Matt Deacalion