[英]How to set process.env variable inside npm script?
I created a new Vue app ( based on Vite ) using npm init vue@latest
and selected Playwright for e2e tests.我使用
npm init vue@latest
创建了一个新的 Vue 应用程序(基于 Vite),并选择了 Playwright 进行端到端测试。 The generated configuration file provides a field to set the headless mode生成的配置文件提供了一个字段来设置headless模式
const config: PlaywrightTestConfig = {
// ...
use: {
// ...
headless: !!process.env.CI,
},
// ...
};
but I don't know how to set this env variable.但我不知道如何设置这个环境变量。 The generated script
生成的脚本
"test:e2e": "playwright test",
does not run in headless mode.不以无头模式运行。 So I tried to set this variable before running it.
所以我试图在运行它之前设置这个变量。 Scripts I tried
我试过的脚本
"test:e2e:ci": "NODE_ENV=CI playwright test"
"test:e2e:ci": "set NODE_ENV=CI& playwright test"
"test:e2e:ci": "set NODE_ENV=CI & playwright test"
"test:e2e:ci": "set CI=true & playwright test"
"test:e2e:ci": "set NODE_ENV=CI && playwright test"
"test:e2e:ci": "set CI=true && playwright test"
Does someone know how to fix the ci script?有人知道如何修复 ci 脚本吗?
This is the generated config file这是生成的配置文件
https://pastebin.com/tbXNuscy https://pastebin.com/tbXNuscy
there are many uses of process.env.CI
and I'm looking for a way to set this on the fly ( inside the npm script where I need it ) process.env.CI
有很多用途,我正在寻找一种方法来即时设置它(在我需要它的 npm 脚本中)
You may add a .env
file in your project folder您可以在项目文件夹中添加一个
.env
文件
.env .env
NODE_ENV=CI
vite.config.js vite.config.js
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
process.env = {
...process.env,
...loadEnv(mode, process.cwd())
};
return defineConfig({
// ...
});
};
Then you can use the configs in .env
like below:然后你可以使用
.env
中的配置,如下所示:
in vite.config.js itself, use process.env
在vite.config.js本身,使用
process.env
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
process.env = {
...process.env,
...loadEnv(mode, process.cwd())
};
return defineConfig({
server: {
hmr: {
// you may use process.env here
host: process.env.VITE_APP_HOST,
},
},
});
};
in the other files, use import.meta.env
instead在其他文件中,改用
import.meta.env
import axios from 'axios';
axios.defaults.baseURL = import.meta.env.VITE_API_BASE;
Notice :注意事项:
If the config is needed on the client side, add a VITE_
prefix, or it can't be seen on the client side.如果客户端需要配置,请添加
VITE_
前缀,否则在客户端看不到。
update:更新:
you may use different modes for your test environment and the others您可以为您的测试环境和其他环境使用不同的模式
.env.test .env.test
CI=true
package.json package.json
"test:e2e": "playwright test --mode=test",
.env.prod .env.prod
CI=false
package.json package.json
"prod": "vite build --mode=prod",
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.