Search code examples
javascriptnode.jsgulpbrowserifycommonjs

How to alias a module with Browserify lib in Gulp?


The Browserify readme describes creating external requires like so: $ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js

Then in your page you can do:

<script src="bundle.js"></script>
<script>
  var through = require('through');
  var duplexer = require('duplexer');
  var myModule = require('my-module');
  /* ... */
</script>

This works if you want to do use the command line, but I'd like to use Browserify in a gulpfile. But there seems to be no way to add a name to a module like ./myfile-js:my-module in the example. If there's an option for it, I haven't found it. The only way to require my module in the way that they describe is to do require(3) because Browserify seems to give numbers to the modules, but these numbers change and clearly this is not desirable.

EDIT: My current solution is to do this:

var shell = require('gulp-shell');

gulp.task('browserify', shell.task([
  'browserify -r ./src/bundle.js:bundle > ./build/bundle.js'
]))

This is a workaround and not optimal if I want to take full advantage of the Gulp pipeline. I'd like to know how this can be done without the command line or, if not, why this is only something that can be done via CLI?


Solution

  • b.require() with expose option.

    function bundle () {
      browserify()
      .require("./myfile-js", {expose: "my-module"})
      .require("through")
      .require("duplexer")
      .bundle()
      /* ... */
    }
    
    gulp.task("browserify", bundle);
    

    Browserify-Gulp integration

    The other answers suggest that vinyl-source-stream is a requirement here, but that's not necessarily true. You haven't illustrated how you're integrating Browserify and Gulp. You only need vinyl-source-stream if you're actually doing some integration between Browserify and Gulp beyond just wrapping a Browserify bundling operation in a Gulp task (which people fairly commonly do), like running a Gulp plugin on the bundled output. For example, you can just do this:

    var fs = require("fs");
    
    gulp.task("browserify", function () {
      return browserify(/* ... */)
        /* ... */
        .bundle()
        // But if you're doing something with Gulp here you should use
        // `vinyl-source-stream` and pipe to `gulp.dest()`.
        .pipe(fs.createWriteStream("./bundle.js", "utf8"));
    });