user3611459
user3611459

Reputation: 3391

React js big in filesize? Correct way to setup gulpfile.js?

I have created a gulpfile.js and a package.json (inclusing all my npm packages), but once building (even without all the additional npm packages), I have a very big final javascript file. It's around 1,5 mb, with React.js, ES2015 and a few other things..

Can anyone tell me why my final build is so big, and how a gulpfile should look like with all the latest versions of the frameworks as of today?

gulpfile:

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('default', function(){
    return browserify('./source/app.js')
        .transform(babelify, {presets: ["es2015", "react"]})
        .bundle()
        .pipe(source('build.js'))
        .pipe(gulp.dest('./build/'));
});

and my packages.json

"devDependencies": {
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babelify": "^7.3.0",
    "browserify": "^13.0.1",
    "gulp": "^3.9.1",
    "vinyl-source-stream": "^1.1.0"
},
"dependencies": {
    "react": "^15.0.2",
    "react-addons-update": "^15.0.2",
    "react-bootstrap": "^0.29.4",
    "react-dom": "^15.0.2"
}

Thank you (a lot)!

Upvotes: 0

Views: 316

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

There are couple of important steps you're missing if you want to create minified production builds.

Environment

The unminified version of React contains a certain amount of code that can be safely omitted for production. You'll find it in conditional statements like this:

if(process.env.NODE_ENV !== 'production') {
  // ... 
}

The first is to include envify as part of your pipeline, then set up the appropriate environment variable from gulp.

gulp.task('default', function(){
  process.env.NODE_ENV = 'production';
  return browserify('./source/app.js')
    ...
});

When this runs, it will substitute the process.env.* references for their literal values.

// with process.env.NODE_ENV = 'production'
if(process.env.NODE_ENV !== 'production') { }
// becomes
if('production' !== 'production') { }

Minification

Smart minifiers, like UglifyJS2 will spot this in their static analysis pass and recognize that the statement contains dead code (code that will never run) and can safely remove it before further minification.

The minifier will also remove comments, rename most of your variables and delete lots of whitespace to shrink the filesize.

Once you've eliminated the dead code and minified the rest, you should find that the gzipped size of the resulting bundle is much more reasonable. Otherwise, you might be interested in checking out Preact (which is only 3kb) and some of the other alternatives to React.

Upvotes: 3

Related Questions