Create separate JavaScript bundles with a shared common library using Browserify and Gulp

这一生的挚爱 提交于 2019-11-28 15:21:30

Figured it out, sharing the learns:

Code example:

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

gulp.task('browserify', function(){

    return browserify({
        entries: ['blog.js', 'page.js']
    })
    .plugin(factor, {
        // File output order must match entry order
        o: ['bundle/blog.js', 'bundle/page.js']
    })
    .bundle({
        debug: true
    })
    .pipe(source('common.js'))
    .pipe(gulp.dest('bundle/'));

});

The key difference between this output and the diagram, is that the common.js file is automatically generated based on common depenedencies between blog.js and page.js. This is described in the factor-bundle documentation.

Notes:

  • I found that Node would throw an error if the output files didn't already exist. I'm unsure why as I would have assumed that factor-bundle would simply write a stream to the outputting file regardless of whether it was there or not. As a workaround, after 'cleaning' the output directory, I simply created 'placeholder' files to keep it happy.

  • I haven't figured out how to access the factor-bundle stream event when using it as a browserify plugin (it may not even be possible), so any further work on the output files (such as uglifying etc) would likely need to be done somewhere else in the pipeline, possibly with another browserify plugin, or even after the fact.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!