Search code examples
javascriptnode.jsgulpbrowserify

Prevent browserify from including module's dependencies


I'd like to use my NodeJS module in the browser - so I'm using browserify to process it.

Now, how can I stop browserify from including the module's dependencies in the bundle file? In this case the dependency is lodash and I'll be loading it separately in the index.html.

Here's what I've got so far:

index.html

<script src="lodash.js"></script>
<script src="my-module.js"></script>

index.js

var _ = require('lodash');

_.each([0, 1, 2], function(item) {
    console.log(item);
});

gulp.js

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

gulp.task('browserify', function() {
  return browserify()
    .require('./index.js', {
      expose: 'my-module'
    })
    .bundle()
    .pipe(source('my-module.js'))
    .pipe(gulp.dest('./'));
});

Solution

  • browserify-shim offers the option of setting up globals.

    Here are the changes I've made to my code.

    package.json

    {
      "browserify-shim": {
        "lodash": "global:_"
      },
      "browserify": {
        "transform": ["browserify-shim"]
      }
    }
    

    gulp.js

    gulp.task('browserify', function() {
      return browserify('./index.js')
        .require('./index.js', {
          expose: 'my-module'
        })
        .transform('browserify-shim', {
          global: true
        })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./'));
    });