比较环境变量和常量时,字符串比较在Javascript中不起作用

Mig*_*gel 6 javascript environment-variables node.js

我们有一个使用CRA 1.x创建的简单React应用程序。

We installed dotenv to use environment variables on the project and our variables are included on the .env and .env.development files like this:

.env

REACT_APP_LOGGER=LOGGER
Run Code Online (Sandbox Code Playgroud)

.env.development

REACT_APP_LOGGER=NO_LOGGER
Run Code Online (Sandbox Code Playgroud)

Then in the code we have this logic:

if(process.env.REACT_APP_LOGGER === "LOGGER") {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

On local builds with webpack 4 in development mode the if is true, and on production mode is false.

But on azure, in both cases is false

process.env.REACT_APP_LOGGER === "LOGGER" // false
Run Code Online (Sandbox Code Playgroud)

We have checked the value of process.env.REACT_APP_LOGGER and it is "LOGGER" type of string but the code is returning weird values:

console.log(process.env.REACT_APP_LOGGER)
console.log(process.env.REACT_APP_LOGGER === "LOGGER")
console.log(process.env.REACT_APP_LOGGER == "LOGGER")
console.log(typeof process.env.REACT_APP_LOGGER)
Run Code Online (Sandbox Code Playgroud)

This is the output generated by the previous code:

LOGGER
false
false
string
Run Code Online (Sandbox Code Playgroud)

Is there something I´m doing wrong? The weird part is that we have other string comparisons like this one and they are comparing correctly.

process.env.NODE_ENV === "production" // true 
Run Code Online (Sandbox Code Playgroud)

EDIT: When we look at the transpiled code we see the following:

console.log("LOGGER"),
console.log(!1),
console.log(!1),
console.log(f("LOGGER"));
Run Code Online (Sandbox Code Playgroud)

So I guess that means the comparison is done during build time (and as this is a constant it makes sense).

Mig*_*gel 6

解决方案是将两者都传递给 stringify,如下所示:

JSON.stringify(process.env.REACT_APP_LOGGER) === JSON.stringify("LOGGER")
Run Code Online (Sandbox Code Playgroud)

这样,我们就可以将两个变量转换成相同的字符串格式,长度相同,值相同,但是Azure Process注入的环境变量并不相同。

  • 就我而言,它仍然不起作用,因为战争结束时有一个尾随空格。我使用了 `set NODE_ENV=develop && ` 然后是另一个命令。也许它会帮助某人调试,因为尾随空格没有显示在 console.log 中 (4认同)
  • 你通过给出有关尾随空格的提示为我节省了很多时间@ExceptionalNullPointer。`NODE_ENV=develop && node app.js` 不适合我。但“NODE_ENV=develop&node app.js”正在工作。 (2认同)

小智 5

这是因为文件中值的长度config。我们可以通过使用来解决这个问题.trim()

if (process.env.NODE_ENV.trim() === 'development') {
    app.use(morgan('dev'));
}
Run Code Online (Sandbox Code Playgroud)