Make browserify modules external with Gulp

ぐ巨炮叔叔 提交于 2020-01-01 03:06:06

问题


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

I guess I have to use external and alias but I am not sure what is the proper way to do it

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


回答1:


Here are a couple of gulp tasks that would help to build your common lib.js and the client.js bundles separately.

Note that you have to tell browserify to b.require() lib/*.js when bundling lib.js, and you have to tell it to b.external() the libraries that will be 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` 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']);



回答2:


Are you looking for external requires?

To use with gulp-browserify, check the README

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

Should work with bundle.require as well.



来源:https://stackoverflow.com/questions/21485440/make-browserify-modules-external-with-gulp

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