ismay ismay - 8 months ago 16
Javascript Question

How do I export my browserified modules for requiring in the browser?

I have several js modules that I bundle with browserify in gulp:

gulp.task('build:js', ['clean:js'], function () {
debug: true,
entries: paths.js.src
.transform('babelify', { presets: ['es2015'] })

It outputs a single
. However, when bundled like this I can't
individual modules in the browser. Which I'd like to do, because I don't want to always initiate every module (some are page specific). Instead of that I'd like to be able to use
var someModule = require('some-module');
on a page alongside the bundle.

Now I couldn't really find anything about this in the documentation, since it only documents the commandline options (and not the js api). This answer shows that a module can be required and exposed from gulp, but that would expose my entire bundle, and not the modules of which it is composed.

A solution would be to bundle all my modules separately, exclude dependencies (so they won't be duplicated across bundles) and then concatenate that. But that doesn't really seem like a viable solution because:

  1. The modules might have trouble resolving dependencies since everything is bundled separately, and thus dependencies would have to be resolved in-browser. Not ideal and prone to breakage I think.

  2. It is very labour intensive since I use a lot of modules, and each will have to be exported manually in gulp, dependencies excluded and referenced in my templates. There are ways to automate it, but this doesn't exclude shared dependencies.

So how do I solve this? How can I require the bundles of which my js is composed separately in the browser, for client side use?


So what I ended up doing is something else. What I was asking kind of went against the way that browserify works, even though it's possible. Maybe eventually when HTTP2 imports and js modules can be used in all major browsers this'll be easier.

For now, I just have a global bundle for the scripts that run on every page, including all my third party libraries. And then for each page I have an separate entry point with the local modules that it needs. This is so far the most maintainable solution.