Windows 上的节点环境变量 [英] Node Environmental variable on Windows
问题描述
我注意到这种奇怪的行为,这没什么大不了的,但让我很烦.
I noticed this strange behavior which is not a big deal, but bugging the heck out of me.
在我的 package.json 文件中,在脚本"部分下,我有一个开始"条目.它看起来像这样:
In my package.json file, under the "scripts" section, I have a "start" entry. It looks like this:
"scripts": {
"start": "APPLICATION_ENV=development nodemon app.js"
}
在 Mac 终端上输入 npm start
工作正常,并且 nodemon 按预期使用正确的 APPLICATION_ENV 变量运行应用程序.当我在 Windows 环境中尝试相同的操作时,出现以下错误:
typing npm start
on a Mac terminal works fine, and nodemon runs the app with the correct APPLICATION_ENV variable as expected. When I try the same on a Windows environment, I get the following error:
'APPLICATION_ENV' 不是内部或外部命令,也不是可运行的程序或批处理文件."
"'APPLICATION_ENV' is not recognized as an internal or external command, operable program or batch file."
我已经尝试过 git-bash shell 和普通的 Win CMD 提示,同样的处理.
I have tried the git-bash shell and the normal Win CMD prompt, same deal.
我觉得这很奇怪,因为直接在终端中输入命令(而不是通过 npm start 通过 package.json 脚本)工作正常.
I find this odd, because typing the command directly into the terminal (not going through the package.json script via npm start) works fine.
有没有其他人看到过这个并找到了解决方案?谢谢!!
Has anyone else seen this and found a solution? Thanks!!
推荐答案
为了在脚本中跨平台使用环境变量,请安装并利用 跨环境.
For cross-platform usage of environment variables in your scripts install and utilize cross-env.
"scripts": {
"start": "cross-env APPLICATION_ENV=development nodemon app.js"
}
该问题在提供给 cross-env
的链接中得到了很好的解释.内容如下:
The issue is explained well at the link provided to cross-env
. It reads:
当您像这样使用 NODE_ENV=production
设置环境变量时,大多数 Windows 命令提示符都会卡住.(Windows 上的 Bash 除外,它使用本机 Bash.)同样,Windows 和 POSIX 命令使用环境变量的方式也有所不同.在 POSIX 中,您使用:$ENV_VAR
,而在 Windows 上,您使用 %ENV_VAR%
.
Most Windows command prompts will choke when you set environment variables with
NODE_ENV=production
like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables. With POSIX, you use:$ENV_VAR
and on windows you use%ENV_VAR%
.
这篇关于Windows 上的节点环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!