Question

I am using browserify and browserify-shim in a project, run through gulp using gulp-browserify.

    gulp.src(['./resources/js/main.js'])
    .pipe(browserify({
        shim: {
            angular: {
                path: './node_modules/angular/angular.js',
                exports: 'angular'
            },
            'angular-animate': {
                path: './node_modules/angular-animate/angular-animate.js',
                exports: 'ngAnimate',
                depends: {
                    angular: 'angular',
                    jQuery: 'jQuery'
                }
            },
            [...]
        }
    }))
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./web/js'));

This setup works fine and, for most parts, as intended. However, Browserify will always include all shimmed libraries in the build, even if none of them is called by require().

The documentation seems to be non-existant on this topic. Is there a way to prevent this? It seems very counter-intuitive to me - the build should only contain what I actually require.

(Update: I installed angular and other libs using napa/npm)

Était-ce utile?

La solution

When you shim with Browserify, it's making those libraries (and specifically the objects you tell it to "export") global. The convention is to still use require() for those libraries, however, doing so is just best practice so that if the library were to convert to module.exports down the road, you won't have to replace the global references in your code. Plus, it's nicer to list all of the files you require at the top in good node form. :)

So to answer your question, by shimming those libraries, you've told browserify to include them as global variables so they can be used anywhere, so they'll be included in the build automatically, regardless of whether you require() them.

If you want to include some and not others based on something like gulp.env, you could try building the options object separately and passing it into the browserify function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top