'How can I use dotenv with vite/petite vue?

How can I use .env variable in petite-vue project? when run yarn vite it give me error: process is not defined

The file structure is this:

Root
|_index.html
|_vue-index.ts

I've imported vue script in index.html and with something like console.log('Hello') connected to a button work fine so it's not a problem of importing script. But, when I try to console.log(process.env.URL) it returns me that error and @click don't do nothing.

# .env
URL=http://example.com
// vue-index.ts
import { createApp } from 'petite-vue';
import 'dotenv/config';

createApp({
  print() {
   console.log(process.env.API_URL);
  },
}).mount('#app');

The problems seems to be in import.meta.env. things by vite. MY problem was that with TS that things is not permitted without changing tsconfig.json moule options to esnext or other.

Someone that can explain me how to use it? If I run this with ts-node work properly.

import 'dotenv/config'

console.log(processs.env.API_URL)


Solution 1:[1]

For whoever come's here looking to solve the problem I've found that the most simple way of doing it is with this plugin.

Just add this few line to vite.config.*

// vite.config.ts
import EnvironmentPlugin from 'vite-plugin-environment'; // Here we import the plugin that expose env variable when vite bundle up the app

const config = {
  root: './src',

  // Here you can define which env to expose with prefix params
  // i.e.: EnvironmentPlugin('all', {prefix: 'test'}) => test_env_var == true, env_var == false
  plugins: [EnvironmentPlugin('all', {prefix: ''})], 
};

export default config;

Solution 2:[2]

1- Create .env file in your home directory. It is not in the /src folder.

2- Only keys starting with VITE_ can be accessed in the .env file from within Vite + Vue 3.

Example .env file content

VITE_BACKEND_PORT = 5000
VITE_MAP_KEY = eae5454ii5557772142
BACKEND_PORT = itIsInaccessible

Example of using in App.vue file

<script setup>
const backendPort = import.meta.env.VITE_BACKEND_PORT;
const mapKey = import.meta.env.VITE_MAP_KEY;
console.log(backendPort)
console.log(mapKey)
</script>
<template>
{{backendPort}} {{mapKey}}
</template>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lorenzo Monaco
Solution 2 Sezgin İbiş