[英]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'));
});
dotenvCypress()
必須在setupNodeEvents()
中返回.env
文件中獲取所有環境變量,您必須將true
作為第三個參數傳遞給dotenvCypress()
。 否則,只有以CYPRESS_
為前綴的變量可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.