Bests practice for Browserify in large web projects - Gulp

后端 未结 2 447
我寻月下人不归
我寻月下人不归 2020-12-28 10:19

Here is the thing,

I come from a world where you have several js files included to a web page. Some are always included in the page

相关标签:
2条回答
  • 2020-12-28 10:35

    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.

    0 讨论(0)
  • 2020-12-28 10:38

    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.

    0 讨论(0)
提交回复
热议问题