Bests practice for Browserify in large web projects - Gulp

依然范特西╮ 提交于 2019-11-30 02:22:16

It depends on your particular case. Browserify is often used for single page apps where a single bundle is often the best solution. You are using it in a non single-page application.

I see two choices:

  1. Bundle everything together. If you have a relatively small app, this will be the easiest and maybe most efficient solution (because of browser caching). Just include all your page specific modules along with your other ones.

  2. Create separate bundles. You could create a bundle for each page, or a bundle for groups of related pages. Browserify will create a separate file for each bundle and you can include them independently on each page.

<script src="common-bundle.js"></script>
<script src="bundle-for-this-page.js"></script>

You will still be able to use require() across modules.

You could separate each page's javascript into a separate directory and use that to automate gulp. With gulp it could look something like:

var pageDirs = ['page1', 'page2'];

pageDirs.forEach(function(pageDir) {
    gulp.task('browserify-' + pageDir, function() {
        gulp.src(pageDir + '/index.js')
            .pipe(browserify())
            .on('prebundle', function(bundle) {
                bundle.external('./common-bundle');
            })
            .pipe(gulp.dest('./build/' + pageDir))
    });
});

gulp.task('browserify-all', pageDirs.map(function(pageDir) {
    return 'browserify-' + pageDir;
});

Create a separate task for browserifying your common bundle.

Thanks for your Answer. It get me on track. After a lot of other research, I found the exact script I needet to browserify multiple entry points files whithout havin to call it manually on every of them:

var gulp = require('gulp');
var gutil = require('gulp-util');
var browserify = require('browserify');
var transform = require('vinyl-transform');

// BROWSERIFY
gulp.task('browserify', function(){
    var browserified = transform(function(filename) {
        var b = browserify(filename);
        b.transform(reactify);
        return b.bundle();
    });

    return gulp.src(JS_SRC)
        .pipe(browserified)
        //.pipe(uglify())
        .pipe(gulp.dest(JS_DEST))
        .pipe(notify({message: 'Browserify task completed.'}));
});

This script takes every js file in the JS_SRC dir and assume it's a browserify entry point.

This worked fine for me.

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