Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('./'));
});
like image 730
Pablo Avatar asked Feb 25 '15 19:02

Pablo


2 Answers

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('./'));
});
like image 163
Pablo Avatar answered Oct 07 '22 14:10

Pablo


There's an option to exclude files:

Usage: browserify [entry files] {OPTIONS}
[...]
--ignore, -i Replace a file with an empty stub. Files can be globs.
--exclude, -u Omit a file from the output bundle. Files can be globs.

https://github.com/substack/node-browserify#usage

And the corresponding exclude function:

b.exclude(file)

Prevent the module name or file at file from showing up in the output bundle.

If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.

So you should try this:

return browserify()
  .require('./index.js', {
    expose: 'my-module'
  })
  .exclude('lodash.js')
  .bundle();
like image 44
NikitaBaksalyar Avatar answered Oct 07 '22 14:10

NikitaBaksalyar