[英]How can I use SECRET_ENV in npm scripts inside of package.json?
I have a secret key called API_KEY
that I want to access inside of package.json
's scripts
.我有一个名为API_KEY
的密钥,我想在package.json
的scripts
中访问它。
{
"scripts": {
"start": "web-ext run --api-key=API_KEY"
}
}
My .env
file contains API_KEY
:我的.env
文件包含API_KEY
:
API_KEY=abc123
How can I access the value of API_KEY
inside package.json
's scripts
while still keeping it a secret because I need to push package.json
publicly? How can I access the value of API_KEY
inside package.json
's scripts
while still keeping it a secret because I need to push package.json
publicly?
Currently, I do the following which works but not cross-platform:目前,我做了以下工作但不是跨平台的:
{
"scripts": {
"start": "web-ext run --api-key=$API_KEY"
}
}
And when running start
script I do it like:在运行start
脚本时,我会这样做:
API_KEY=abc123 npm start
This works thanks to Bash Programming Language but it doesn't work on Windows.这要归功于 Bash 编程语言,但它不适用于 Windows。 I need to replace $API_KEY
in start
script with %API_KEY%
.我需要用%API_KEY%
替换start
脚本中的$API_KEY
。 But I want it to be cross-platform.但我希望它是跨平台的。 Is there any other way?还有其他方法吗?
The only other viable answer to this I found so far is a bit hacky:到目前为止,我发现的唯一其他可行的答案有点老套:
{
"scripts": {
"start": "web-ext run --api-key=$(grep API_KEY .env | cut -d '=' -f2)"
}
}
[ https://stackoverflow.com/a/58038814/1822977 ] [ https://stackoverflow.com/a/58038814/1822977 ]
You can simply require "dotenv" lib, and access var from process.env.{SOME_KEY}您可以简单地要求“dotenv”库,并从 process.env.{SOME_KEY} 访问 var
1) You can use 'npm env-cmd ' as a devDependencies
. 1)您可以使用 'npm env-cmd ' 作为devDependencies
。
Setting the environment from a file从文件设置环境
Environment file ./.env
环境文件./.env
# This is a comment
API_KEY=abc123
Package.json Package.json
{
"scripts": {
"start": "env-cmd web-ext run"
}
}
2) You can use 'npm cross-env ' as a devDependencies
. 2)您可以使用 'npm cross-env ' 作为devDependencies
。
Run scripts that set and use environment variables across platforms跨平台运行设置和使用环境变量的脚本
Usage用法
{
"scripts": {
"start": "cross-env API_KEY=abc123 web-ext run"
}
}
You can try something like this:你可以尝试这样的事情:
cmd /C "set API_KEY=abc123 && npm start"
As Viper_Sb says here :正如Viper_Sb 所说:
/C exits the new cmd right away after running, if you produce output with the new one it will still be visible in the parent window. /C 运行后立即退出新的 cmd,如果您使用新的 output 生成 output,它仍将在父 window 中可见。
You can opt to use /K in which case the new cmd window stays open at the end of the run.您可以选择使用 /K 在这种情况下,新的 cmd window 在运行结束时保持打开状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.