How to use a .env file with Vite and Vue?
The answer is simple
When you create a vite project, vite automatically creates a config file for us. This config file is through which we will connect to our servers. It is through which we can declare our ports. Now, it is always a good software practice to declare important things such as the address of the server or the port number as env variables. And this is the way to do it.
At first you need to import something called a load env file and the rest is easy and breezy. This is the way I did it.
import { defineConfig, loadEnv } from 'vite'import vue from '@vitejs/plugin-vue'export default defineConfig(({mode})=>{const env = loadEnv(mode, process.cwd());return{plugins: [vue()],build:{outDir:"./wwwroot/app/", sourcemap:true },server: {proxy: {"^/api": {target:env.VITE_PORT,changeOrigin: true,secure: false,withCredentials: true,rewrite: (path) => path.replace(/^\/api/, ``),
},
},
port:4000},}
})
This is my vite.config.js file. I am using an API in my software which is why I needed to make the api proxy so that I do not get axios errors. This is what my .env file looks like
VITE_PORT=http://serveraddressMAIN_METERS=main
I am receiving data from a server address which is connected to my software with api and this server address cannot be exposed in the config file for which reason I have to use a .env file. Now this main_meters is also part of the software it is the homepage. I had to make the homepage a vuex state. Hence in my store/index.js file I have called this main_meters by using
currentRoute:import.meta.env.MAIN_METERS,
This is how you can use a .env file in any part of the code. Any data in the .env file can be used in the entire program by using import.meta.env.variable and any data in the .env file can be used by using env.variable in the config file except in the config file load env needs to be imported and a const named env or anything can be created from loadenv. Hence, everything will work out properly. Altogether, the sky will always be clear and the future of all coders will be bright everywhere. Hope, this helps!
Spread the love like a spread operator
…Love
Samanja