sixtyone
sixtyone

Reputation: 29

How can I get Vite env variables?

I am using Quasar, Vue 3, Vite, Cypress in my project. I don't know how to get .env variables (e.g. VITE_API_URL) and to set in cypress.env.json. Before Vite I used webpack and I know how to do it.

I don't want to define twice same variable, first in .env then in cypress.env.json.

Upvotes: 2

Views: 2168

Answers (3)

Simran Singh
Simran Singh

Reputation: 2869

You can use cypress-plugin-dotenv to share .env files with Cypress app. This plugin is also introduced on official cypress plugins docs. It works for Vite with react or vue, create-react-app, Turborepo, and many other frameworks and setups.

Installation:

npm install cypress-plugin-dotenv

Usage:

import { dotenv } from 'cypress-plugin-dotenv';
// or
const dotenv = require('cypress-plugin-dotenv');

export default defineConfig({
   e2e: {
     setupNodeEvents: (_, config) => {
       return dotenv(config);
     }
   }
});

Now go to your spec file and just use Cypress.env('YOUR_ENV')

Upvotes: 0

Udo.Kier
Udo.Kier

Reputation: 241

You can use the dotenv package directly, merging the result in with the env section of your cypress config.

.env

VITE_API_URL: "http://example.com"

cypress.config.js

const { defineConfig } = require("cypress");
const dotenv = require('dotenv')
const env = dotenv.config('./.env').parsed

module.exports = defineConfig({
  'component': {
    // component config here
  },
  env: {
    login_url: '/login',
    ...env,                        // merge here with spread operator
  },
});

Settings page in the Cypress runner

env: {
  login_url: '/login',
  VITE_API_URL: 'http://example.com',
},

Upvotes: 4

DJSDev
DJSDev

Reputation: 993

There is a plugin called cypress-dotenv for this very purpose. It allows you to share your .env file variables between your app and cypress tests.

Install

npm install --save-dev cypress-dotenv

# For typescript
npm install --save-dev @types/cypress-dotenv

Example

Example .env file

VITE_API_URL=https://vite-api-url.com

In your cypress.config.js, run the plugin dotenvCypress() under setupNodeEvents():

import { defineConfig } from "cypress";
import dotenvCypress from 'cypress-dotenv';

export default defineConfig({
  component: {
    devServer: {
      framework: "vue",
      bundler: "vite",
    },
    setupNodeEvents(on, config) {
      return dotenvCypress(config, undefined, true);
    },
  },
});

Then in your test:

it('works', () => {
  cy.log(Cypress.env('VITE_API_URL'));
});

Notes

  1. dotenvCypress() must be returned in setupNodeEvents()
  2. To get all the env variables from your .env file, you have to pass true as the third argument to dotenvCypress(). Otherwise, only vars prefixed with CYPRESS_ will be available.

https://www.npmjs.com/package/cypress-dotenv

Upvotes: 0

Related Questions