Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use factor-bundle with browserify programmatically?

I want to use factor-bundle to find common dependencies for my browserify entry points and save them out into a single common bundle:

https://www.npmjs.org/package/factor-bundle

The factor-bundle documentation makes it seem very easy to do on the command line, but I want to do it programmatically and I'm struggling to get my head around it.

My current script is this (I'm using reactify to transform react's jsx files too):

var browserify = require('browserify');
var factor = require('factor-bundle')
var glob = require('glob');

glob('static/js/'/**/*.{js,jsx}', function (err, files) {     
  var bundle = browserify({
    debug: true
  });

  files.forEach(function(f) {
    bundle.add('./' + f);
  });
  bundle.transform(require('reactify'));

  // factor-bundle code goes here?

  var dest = fs.createWriteStream('./static/js/build/common.js');
  var stream = bundle.bundle().pipe(dest);
});

I'm trying to figure out how to use factor-bundle as a plugin, and specify the desired output file for each of the input files (ie each entry in files)

like image 615
Andrew Ingram Avatar asked Mar 06 '14 12:03

Andrew Ingram


1 Answers

This answer is pretty late, so it's likely you've either already found a solution or a work around for this question. I'm answering this as it's quite similar to my question.

I was able to get this working by using factor-bundle as a browserify plugin. I haven't tested your specific code, but the pattern should be the same:

var fs = require('fs'),
    browserify = require('browserify'),
    factor = require('factor-bundle');

var bundle = browserify({
    entries: ['x.js', 'y.js', 'z.js'],
    debug: true
});

// Group common dependencies
// -o outputs the entry files without the common dependencies
bundle.plugin('factor-bundle', {
    o: ['./static/js/build/x.js', 
        './static/js/build/y.js', 
        './static/js/build/z.js']
});

// Create Write Stream
var dest = fs.createWriteStream('./static/js/build/common.js');

// Bundle
var stream = bundle.bundle().pipe(dest);

The factor-bundle plugin takes output options o which need to have the same indexes as the entry files.

Unfortunately, I haven't figured out how to do anything else with these files after this point because I can't seem to access factor-bundle's stream event. So for minification etc, it might need to be done also via a browserify plugin.

like image 75
justrhysism Avatar answered Nov 17 '22 10:11

justrhysism