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 () {
  browserify({
    debug: true,
    entries: paths.js.src
  })
    .transform('babelify', { presets: ['es2015'] })
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(gulp.dest(paths.js.dist));
});

It outputs a single bundle.js . However, when bundled like this I can't require 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:

  • 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.
  • 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.

    链接地址: http://www.djcxy.com/p/32898.html

    上一篇: 混合browserify和webpack外部

    下一篇: 如何导出浏览过的模块以便在浏览器中进行浏览?