How to use vite env variables in vite.config.js?

Member

by gilbert , in category: Javascript , a year ago

How to use vite env variables in vite.config.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , a year ago

@gilbert 

To use vite env variables in vite.config.js, you can access them through the process.env object. Here is an example of how you can use env variables in your vite.config.js file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { defineConfig } from 'vite'

export default defineConfig({
  base: process.env.BASE_URL || '/',
  plugins: [
    // you can also use env variables in your plugins configuration
  ],
  build: {
    outDir: process.env.OUT_DIR || 'dist'
  }
})


In this example, we are using process.env.BASE_URL and process.env.OUT_DIR to set the base URL and output directory for the build respectively. You can define your own env variables in your .env files and access them in your Vite configuration file in the same way.


Make sure to prefix your env variables with VITE_ to make them available in your Vite configuration. For example, if you have an env variable named API_URL, you should define it as VITE_API_URL in your .env files.

Related Threads:

How to load environment variables from .env file using vite?
How to use linux variables in .env of vue.js?
How to use the .env files config from webpack to vite?
How to overwrite .env file variables in laravel?
How to access env variables in index.html in ember.js?
How to load env in vite svelte for production?