Search code examples
javascriptgulpbundlebrowserifyuglifyjs

Remove javascript code from bundle during production build


I noticed that ReactJS has some debug messages that appears only in development mode.

When I set process.env.NODE_ENV = 'production'; in my gulpfile.js before bundling, the debug messages disappears.

How can I write such code, that appears only in development (debug) build but are not bundled into production build?

something like:

function sayHello(message){
  #IF DEBUG
     if (!message) console.log("message cannot be null");
  #ENDIF

  alert(message);
}

EDIT: when I tried to use if (process.env.NODE_ENV !== 'production') then gulp-uglify correctly removed the code from bundle in production build. However, at runtime (in browser), process.env.NODE_ENV is undefined and the condition on never met.

How it is possible, that it works in react?

var browserify = require("browserify");
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');

process.env.NODE_ENV = 'production';

var bundler = browserify({ debug: false })
   .require('react')
   .require('react-dom')

bundler.bundle()
    .pipe(source("reactbundle.js"))
    .pipe(buffer());
    .pipe(uglify())
    .pipe(gulp.dest(paths.distDir + 'scripts'));

Solution

  • I don't have a typescript version but have you tried gulp-remove-code? You can surround your JavaScript with some comments to remove whatever code you want when running your production build. This is from the above linked page:

    var removeCode = require('gulp-remove-code');
    
    gulp.src('./src/file.js')
      .pipe(removeCode({ production: true }))
      .pipe(gulp.dest('./dist'))
    
    
    //removeIf(production) 
    value = JSON.stringify({key: 'value'}, null, 2);
    //endRemoveIf(production)