21

When trying to build an angular-webpack application by running the build command from this scripts list on the package.json:

"scripts": {
    "test": "NODE_ENV=test karma start",
    "build":  "if exist dist rd /s /q dist && mkdir dist && set NODE_ENV=production && webpack && cp app/index.html dist/index.html",
    "start": "webpack-dev-server --content-base app"
  },

this is the result on the console :

$ npm run build

    > webpack-ng-egg@1.0.0 build M:\Learning webpack\egghead.io - AngularJS - Angula
    r and Webpack for Modular Applications\webpack-ng-egg
    > if exist dist rd /s /q dist && mkdir dist && set NODE_ENV='production' && webp
    ack && cp app/index.html dist/index.html

    process.env.NODE_ENV  : 'production'
    process.env.NODE_ENV === 'production' ????  : false
    Hash: c3136b0024cbd48ccb2e
    Version: webpack 1.13.2
    Time: 3185ms
        Asset     Size  Chunks             Chunk Names
    bundle.js  1.23 MB       0  [emitted]  main
        + 10 hidden modules

this is how looks like the webpack.config.js file :

 var webpack = require('webpack');
    var path = require('path');
    var config = {
        context: path.resolve(__dirname, "app"),
        entry:'./app.js',
        output: {
            path : __dirname + '/app',
            filename:'bundle.js' // il ne sera pas généré dans le code, juste en mémoire
        },
        plugins:[
            new webpack.DefinePlugin({
                ON_TEST:process.env.NODE_ENV === 'test'
            })
        ],
        module:{
            loaders: [
            {
              test: /\.js$/,
              exclude: /(node_modules|bower_components)/,
              loader: 'babel', // 'babel-loader' is also a legal name to reference
              query: {
                presets: ['es2015']
              }
            },
             { test: /\.css$/,
               loader: "style-loader!css-loader",
               exclude: /(node_modules|bower_components)/
             },
            {
              test: /\.html$/,
              exclude: /(node_modules|bower_components)/,
              loader: 'raw', // 'babel-loader' is also a legal name to reference
            },
            {  test: /\.styl$/,
               loader: 'style-loader!css-loader!stylus-loader',
               exclude: /(node_modules|bower_components)/
             }
          ]
        },
        devServer:{
            //contentBase:path.join(__dirname, 'dist') // ceci est juste un exemple, si dist est l'endroit ou on aurait généré les fichiers
            inline:true, // les mises à jour de style ne sont plus affichés instantnément avec cette option donc j'ai ajouté le watch:true et çà marché!!!
            watch:true

        }
        /*resolve: {
            extensions: ['', '.js', '.jsx', '.css']
        },
        resolveLoader: {
            root: require('path').resolve(__dirname, "node_modules")
        }*/
    }

    console.log("process.env.NODE_ENV  : " + process.env.NODE_ENV);
    console.log("process.env.NODE_ENV === 'production' ????  : " + (process.env.NODE_ENV == 'production'));
    //config.output.path = path.resolve(__dirname, "dist");
    //console.log("config.output.path  : " + config.output.path);


    if(process.env.NODE_ENV === 'production') {
        console.log("this is the prod env!!!!!!!!!!");
        config.output.path = path.resolve(__dirname, "dist");
    }

    module.exports = config;

the problem here is that when testing (process.env.NODE_ENV === 'production') it never returns true even that it's supposed to be (see what is logged on the console above). I have tried to chage to a simple equality instead the strict one but still get false all the time.

Bardelman
  • 2,176
  • 7
  • 43
  • 70

4 Answers4

52

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 false
console.log(process.env.NODE_ENV === "production"); //False
console.log(process.env.NODE_ENV.trim() === "development"); //True if ran start else false
console.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().

Lavios
  • 1,169
  • 10
  • 22
  • 1
    if your on windows you can get around the extra space issue by executing `cmd /C "set "MY_VAR=true" && ...myProgramContinues"` making sure to wrap the set and the rest of the program values in double quotes `""` – steven87vt Feb 19 '19 at 21:52
  • 1
    Or if you want to keep it concise on windows, just write `set "NODE_ENV=development" && ` (double quotes!). If used in package.json, they may have to be escaped like this: `\"` – ford04 Apr 15 '19 at 09:51
  • 1
    ... Ran into this today.. seriously saved me after trying to figure out what the heck was going on thanks! – Loktar Jul 21 '20 at 19:17
  • You should use the [optional chaining (?.)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) operator `process.env.NODE_ENV?.trim()` in case variable is `undefined`. – Igor Sukharev Mar 24 '23 at 21:04
10

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.

jjj
  • 126
  • 1
  • 4
  • 4
    Thanks for this quick snippet, using an identical setup to this now for React. Only experienced this trailing space on Windows, had no issues on macOS or Linux. – Yusuf Ismail Feb 11 '20 at 16:42
  • Simpler to use the [optional chaining (?.)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) operator `process.env.NODE_ENV?.trim()`. – Igor Sukharev Mar 24 '23 at 21:05
4

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • 1
    thanks for trying but i already tried it too and once again now but in vain – Bardelman Sep 16 '16 at 13:42
  • 2
    You really shouldn't update your question to remove the single quotes, but instead append to the end of your question saying that you also tried removing the single quotes. – mscdex Sep 16 '16 at 13:49
  • 1
    Also, I don't see how it is possible for it to not match after removing the single quotes. You should `console.dir(process.env.NODE_ENV)` and show what that displays anyway. – mscdex Sep 16 '16 at 13:51
  • 1
    for the moment , i changed the NODE_ENV to a numerical value instead of a string and it works. i don't know what was the problem with a string – Bardelman Sep 16 '16 at 14:06
1

I had the same problem and found out my code has spaces. Please trim() it or edit code in package.json.

tnanhpt
  • 11
  • 2