You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
8 Hrs
27 Min
55 Seg
Curso de Vite.js

Curso de Vite.js

Diana Martínez

Diana Martínez

Variables de entorno y modos

14/19
Resources

There are two concepts that we need to understand that can be quite useful: 1. Environment variables, they are external variables to our project and are nothing more than a name assigned to a value. 2. Modes, as we have seen in previous classes, there are two, the development mode (dev) and the production mode (build).

Modes

Let's continue editing our vite.config.js file, but first we must understand that in our function we are receiving some arguments, among them command and mode, command is the command that we use to execute this file and mode tells us if we are in production mode or development mode.

``` import { defineConfig } from "vite";

export default defineConfig(({ command, mode }) => { const port = 8080;

console.log(command: ${command} and mode: ${mode});

return { server: { port }, }; }; }); ```

If we run with dev (npm run dev) we will see that you are using the serve command and the development mode:command: serve and mode: development

But if we run with build (npm run build) the command would be build and the mode would be production:command: build and mode: production.

This can be useful because we can implement a logic depending on the mode we are in, in the following very basic example a message will be printed depending on the mode.

``` import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ command, mode }) => { const port = 8080;

console.log(command: ${command} and mode: ${mode});

if (command === "development") { console.log("Development mode"); } else { console.log("Production mode"); }

return { server: { port }, }; }; }); ```

Environment variables

To access to our environment variables we must first create in the root of the project a file with the name .env and inside this we can create the environment variables that we need.

Structure of an environment variable

The structure of the environment variables is as follows: VITE_VARIABLE_NAME=value, as you will be able to see it is necessary that it begins with the word VITE, so that later it can be recognized.

VITE_NAME="vite demo".

Using environment variables

In the previous example we created an environment variable with the name VITE_NAME, which will store the name of our project. Now, to use it inside vite.config.js we must use loadEnv, a function that is imported from vite and gives us all the variables in the .env file.

Keep in mind that it will only deliver the variables that begin with VITE.

About loadEnv

loadEnv receives two parameters, which are:1. The mode we are in (development mode or production mode). This is because our .env file can also have the name of .env.development or .env.production, if we are in production mode it will bring the variables that are in .env.development, if we are in production mode it will bring the variables of .env.production and if none of these files exist it will bring by default the ones of .env. 2. Location to access via Nodejs to read the file. To access the location we can use process.cwd(), a Nodejs function that gives us the project address.

Example

Next we are going to import loadEnv, create a variable with the name env and inside it use the loadEnv function, giving it the necessary parameters.

````import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ command, mode }) => { const port = 8080; const env = loadEnv(mode, process.cwd());

console.log(command: ${command} and mode: ${mode}); console.log("Environment variables:", env);

if (command === "development") { console.log("Development mode"); } else { console.log("Production mode"); }

return { server: { port }, }; }); ```); ```

Finally we will print the variable env and we will see that it gives us in a JSON format the variables of the file .env

Environment variables: { VITE_NAME: 'vite demo' }

Recap

Now you are able to access the environment variables, something very useful for your professional life, and you can also know in which mode you are and which command you are using. I remind you that you can review this section of the Vite documentation if you want to go deeper into the subject.

Contribution created by: Jofay Zhan Segura

Contributions 9

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

También podemos importar variables de Entorno con el siguiente comando:

import.meta.env.<VariableName>
 

Vite usa dotenv para cargar variables de entorno adicionales desde los siguientes archivos en su directorio de entorno :

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Adicional esta es la documentación de VITE sobre las ENV Variables de entorno VITE

🧩 Más acerca de las variables de entorno

Ideas/conceptos claves

Una variable de entorno es una variable dinámica que puede afectar al comportamiento de los procesos en ejecución en un ordenador. Son parte del entorno en el que se ejecuta un proceso

Apuntes

  • Generalmente, son secretos que solo una máquina en particular debe saber. Ej.: la contraseña de la base de datos

    • Permite almacenar una “contraseña” donde únicamente nos interesa
  • No deben versionarse

    • Peor aún si el repositorio es público, ya que existe montones de bots automatizados para encontrar estas llaves

    <aside>
    💡 En caso de subir por accidente una variable de entorno, no sirve de nada crear otro commit, porque quedará en la historia del repositorio, la mejor solución es crear otra llave de entorno

    </aside>

¿Qué buscamos?

  1. Los secretos no sean compartidos, pero…
  2. Como desarrollador quiero conocer que secretos necesito para que la aplicación funcione.
    • Debe ser una lista clara la cual especifique que llaves necesito para que la aplicación no tenga ningún problema
  3. La aplicación debe ser capaz de cargar y leer nuestros secretos

Implementación

  • Existen diferentes formas de implementar las variables de entorno, una de ellas es la siguiente estructura, donde existe:

Documento de ejemplo

  • Versionado
  • Contiene una lista de llaves necesarias
  • Sin los valores de las llaves ⇒ En el peor de los casos puede existir algún valor, pero es porque nada malo pueda pasar
ACCESS_TOKEN=
URL_DB=

Una copia del documento

  • Ignorado por el versionador (Git).
  • Contiene las llaves necesarias con valores necesarios.
ACCESS_TOKEN=<valor>
URL_DB=<valor>
📌 **RESUMEN:** Las variables de entorno, son la mejor forma de poder guardar contraseñas, llaves, etc. (secretos) ya que estas no son compartidas, establece una lista clara de que secretos necesita la aplicación para que no se rompa y es capaz de cargar y leer dichos valores de la lista de secretos

Para cambiar el prefijo VITE_ a las variables de entorno, pueden cambiar su configuración en el archivo de configuración de vite, modificando la opción envPrefix

// vite.config.js

{
	envPrefix: "PLATZI_"
}

NOTAS DE SEGURIDAD

envPrefix no debe configurarse como ‘’, esto expondrá todas tus variables env y provocará una filtración inesperada de información confidencial. De todas formas, Vite arrojará un error al detectar ‘’.

También tengan en cuenta que para que esto tenga sentido el archivo .env no debe subirse nunca al repositorio en la nube, es decir estar en el .gitignore

El curso mejor explicado de todo plazi. Ojala toros los profesores tuvieran el mismo nivel. Enhorabuena!!

Un ejemplo de archivo de configuración con mis comentarios sobre la clase

.env
VITE_PORT=8000
-----

import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({command, mode}) => {
	// command es el comando con el que se esta ejecutando en npm run "build"
  // mode es el modo que esta ejecutando ["development", "production"]
  // Estas variables están relacioandas con los scripts de package.json que vimos ["dev", "build"]

	const env = loadEnv(mode, process.cwd())

	if(mode === 'development') // Ejecuto algo
  else // ejecuto otra cosa

  return {
    server: {
      port: env.VITE_PORT
    }
  }
})

Estoy viendo que el file “.env” todo lo que se escriba debe ir sin espacio, es cierto, no?

te pasaste diana cual es tu Twitter para seguirte!!!

Carga de variables de entorno en un contexto de acceso a las configuraciones de vite para modo produccion y modo desarrollo