Make browser modules external with Gulp

I have a lib.js library that I want to create from lib/a.js and lib/b.js and be able to use it from script client.js with var a = require('lib/a.js'); and that it works when I just include the compiled lib.js library before client.js (so lib.js should declare a require function that knows about lib/a.js )

I assume I need to use external and alias , but I'm not sure if this is the right way to do this

Also, is it possible to have a Gulp file that automatically creates all the aliases for folders in my library? eg. creates an alias for all files in the lib/ ? directory

+8
javascript gulp browserify
source share
2 answers

Here are a few gulp tasks to help you build your shared lib.js and client.js libraries separately.

Note that you need to tell the browser b.require () lib / *. js when linking lib.js, and you should report this to b.external () libraries, which will be loaded separately when linking the client. Js

 var path = require('path'); var gulp = require('gulp'); var browserify = require('browserify'); var concat = require('gulp-concat'); var transform = require('vinyl-transform'); gulp.task('build-lib', function () { // use `vinyl-transform` to wrap around the regular ReadableStream returned by b.bundle(); // so that we can use it down a vinyl pipeline as a vinyl file object. // `vinyl-transform` takes care of creating both streaming and buffered vinyl file objects. var browserified = transform(function(filename) { // basename, for eg: 'a.js' var basename = path.basename(filename); // define the exposed name that your client.js would use to require(); // for eg: require('lib/a.js'); // -> exposed name should be 'lib/a.js' var expose = 'lib/' + basename; return browserify(filename) .require(filename, { expose: expose}) .bundle(); }); return gulp.src(['./lib/*.js']) .pipe(browserified) .pipe(concat('lib.js')) .pipe(gulp.dest('./dist')); }); gulp.task('build-client', function () { var browserified = transform(function(filename) { // filename = './client.js' // let browserify know that lib/a.js and and lib/b.js are external files // and will be loaded externally (in your case, by loading the bundled lib.js // for eg: <script src='dist/lib.js'>) return browserify(filename) .external('lib/a.js') .external('lib/b.js') .bundle(); }); return gulp.src(['./client.js']) .pipe(browserified) .pipe(gulp.dest('./dist')); }); gulp.task('default', ['build-lib', 'build-client']); 
+13
source share

Are you looking for external requires ?

To use with gulp -browserify check README

 .on('prebundle', function(bundle) { bundle.external('domready'); bundle.external('react'); }) 

Should also work with bundle.require.

-one
source share

All Articles