簡體   English   中英

如何獲取 Vite 環境變量?

[英]How can I get Vite env variables?

我在我的項目中使用了 Quasar、Vue 3、Vite、Cypress。 我不知道如何獲取.env變量(例如VITE_API_URL )並在cypress.env.json中設置。 在Vite之前我用過webpack,我知道怎么做。

我不想定義兩次相同的變量,首先在.env中,然后在cypress.env.json中。

您可以直接使用dotenv package,將結果與 cypress 配置的env部分合並。

.env

VITE_API_URL: "http://example.com"

賽普拉斯.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
  },
});

Cypress runner 中的設置頁面

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

為此,有一個名為cypress-dotenv的插件。 它允許您在應用程序和 cypress 測試之間共享.env文件變量。

安裝

npm install --save-dev cypress-dotenv

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

例子

示例.env文件

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

在您的cypress.config.js中,在dotenvCypress() 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);
    },
  },
});

然后在你的測試中:

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

筆記

  1. dotenvCypress()必須在setupNodeEvents()中返回
  2. 要從.env文件中獲取所有環境變量,您必須將true作為第三個參數傳遞給dotenvCypress() 否則,只有以CYPRESS_為前綴的變量可用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM