npm 如何在package.json中重命名.env变量?

hfwmuf9z  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(171)

What I have

I have multiple projects using Percy for Cypress where I set the PERCY_TOKEN env variable inside the .env file. The token is different for each project. In the CI I set different env variables for each project, but locally I have to do it in the .env file. Because of this, I have to edit the .env file whenever I change between projects.

Goal

I would like to set them in the .env file this way:

PROJECT_A_PERCY_TOKEN=tokenhash1
PROJECT_B_PERCY_TOKEN=tokenhash2

So later I could rename these variables to PERCY_TOKEN , eliminating the need to constantly change the .env file.

What I tried

I'm trying to do this inside the package.json file's scripts property. Unfortunately echo $PROJECT_A_PERCY_TOKEN prints nothing. I know that I could create a shell/python/js script that parses the .env file, then passes the value back or calls npm run directly but I would like to do this without an external script.

Problem

It appears to me that I can't access the env variables inside package.json . Is there a way to rename the variable only using the npm script?

fykwrbwg

fykwrbwg1#

tl;dr

If the package you try to configure has the ability to do configuration via a JavaScript file, you can add the renaming at the beginning of it:

process.env.PERCY_TOKEN = process.env.CYPRESS_PERCY_SALESFORCE_TOKEN;

Explanation

While this isn't the solution I was looking for, it is a workaround for this specific use case. Percy supports JavaScript config files so I migrated my YAML config file, then I logged process.env and the .env file's variables were there, so I just need to copy the correct one. This might work for other packages that support JavaScript config files (or some alternative kind of hook/preloader where custom code can be placed), but if they don't, then the question is still unanswered.

相关问题