javascript - Make browserify modules external with Gulp -
i have library lib.js
want create lib/a.js
, lib/b.js
, able use script client.js
using var = require('lib/a.js');
, works when include compiled lib.js
library before client.js
(therefore, lib.js
has declare require
function knows lib/a.js
)
i guess have use external
, alias
not sure proper way it
also, possible have gulp file creates alias automatically folders in library? eg. creates alias files in lib/
dir?
here couple of gulp tasks build common lib.js , client.js bundles separately.
note have tell browserify b.require() lib/*.js when bundling lib.js, , have tell b.external() libraries loaded separately when bundling 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` wrap around regular readablestream returned b.bundle(); // can use down vinyl pipeline vinyl file object. // `vinyl-transform` takes care of creating both streaming , buffered vinyl file objects. var browserified = transform(function(filename) { // basename, eg: 'a.js' var basename = path.basename(filename); // define exposed name client.js use require(); // eg: require('lib/a.js'); // -> exposed name should '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 lib/a.js , and lib/b.js external files // , loaded externally (in case, loading bundled lib.js // 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']);
Comments
Post a Comment