if(process.env.NODE_ENV === 'production') always false if(process.env.NODE_ENV === 'production') always false windows windows

if(process.env.NODE_ENV === 'production') always false


I had this problem today.

When I used set NODE_ENV=production && something in npm scripts then NODE_ENV=production becomes production + " " with one whitespace after it.

So, we are comparing production with production + " ", this obviously returns false.

package.json

scripts: {    "start": "set NODE_ENV=development && webpack --watch --progress",    "test": "set NODE_ENV=production && webpack"}

Comparisons

console.log(process.env.NODE_ENV.trim() === "production"); //True if ran test else falseconsole.log(process.env.NODE_ENV === "production"); //Falseconsole.log(process.env.NODE_ENV.trim() === "development"); //True if ran start else falseconsole.log(process.env.NODE_ENV === "development"); //False

Working sample of webpack.config.js

const webpack = require("webpack");const dev = process.env.NODE_ENV.trim() !== "production";module.exports = {    entry: "./index.js",    output: {        path: "./",        filename: "parse.js"    },    module: {        rules: [            {                test: /\.js/,                use: "babel-loader",                exclude: /node_modules/            }        ]    },    plugins: dev ? [] : [        new webpack.optimize.UglifyJsPlugin()    ],    target: "node"};

So, use trim().


Use:

if ((process.env.NODE_ENV || '').trim() !== 'production') {

Be careful with the above solutions since NODE_ENV can be undefined and will throw running .trim() on undefined.


The problem is that you're storing the single quotes in NODE_ENV, so the value of NODE_ENV is actually "'production'" instead of just "production". This is evident in your debug output.

Change set NODE_ENV='production' to set NODE_ENV=production and it should work as you expect.