简体   繁体   English

尽管我设置了环境变量,但NODE_ENV显示未定义

[英]NODE_ENV is showing undefined although i set environment variable

I am using webstorm and i tried to set the environment variable using 我正在使用webstorm,并且尝试使用设置环境变量

set NODE_ENV=development

and when i check the for environment variable using 当我使用检查环境变量时

echo%NODE_ENV%

i get development as the answer. 我得到发展作为答案。

But in my node application when i check for the variable using 但是在我的节点应用程序中,当我使用以下命令检查变量时

 var b= process.env.NODE_ENV;

i get 我得到

b:undefined

I even tried using the following in the package.json file 我什至尝试在package.json文件中使用以下内容

"start": "set  node ./bin/www && NODE_ENV=production "

still i am getting undefined. 仍然我越来越不确定。 I dont know whats the problem here. 我不知道这是什么问题。

You should first set the variable and then run the script: 您应该首先设置变量,然后运行脚本:

"start": "set NODE_ENV=production&& node ./bin/www"

Note that this will only work on Windows. 请注意,这仅适用于Windows。 If you want a cross-platform solution, use the cross-env package: 如果您需要跨平台的解决方案,请使用cross-env软件包:

cross-env NODE_ENV=production node ./bin/www

使用导出代替

"start": "export NODE_ENV=production && node ./bin/www"

The following is what works for me, as my goal is trying to keep package dependency to what I really need: 以下是对我有效的方法,因为我的目标是使程序包依存性真正满足我的需求:

"startwin": "SET NODE_ENV=production& SET SOME_TOKEN=123abc& node ./bin/www",
"start": "NODE_ENV=production SOME_TOKEN=123abc node ./bin/www" 

A drawback is each time another environment var is needed, I have 2 places to edit, but that's hardly any effort (at least in my case, yours might be different). 缺点是每次需要另一个环境var时,我都有2个地方可以编辑,但这几乎不需要任何努力(至少就我而言,您的情况可能有所不同)。

If you have a separate config.js being required, make sure it is first. 如果需要单独的config.js,请确保它是第一个。 You may have a race condition. 您可能有比赛条件。

I ran into something like this yesterday. 昨天我遇到了这样的事情。 It may or may not be your issue. 这可能是或不是您的问题。 When I ran my code, my environment variable was undefined. 运行代码时,环境变量未定义。 I moved an entire library into a separate module. 我将整个库移到了单独的模块中。 I required that module. 我需要那个模块。 My problem was that my requires were out of order, so when it asked, it wasn't set yet. 我的问题是我的要求出了问题,所以当它问到时,还没有确定。 I moved my config.js require up above my library package require. 我将config.js的要求移至库包的要求之上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM