Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple bundles with browserify, using modules externally

I want to bundle up some common code as CommonJS modules, and then use those common modules from a different bundle and/or directly from global.

entry1-common.js
-- a.js 
-- b.js 

entry2-app.js
-- x.js
    inside i would like to to access entry1-common's a.js here
    var moduleA = require('./a.js');

<script> 
  // i would also like to access modules from outside
  var moduleA = require('./a.js'); 
  var moduleX = require('./x.js');
</script>

I am using gulp. Some browserify options that seem to be what I need but not quite getting me there:

browserify(bundleConfigs: [{
  entries: './entry1-common.js',
  dest: dest,
  outputName: 'common.js',
  hasExports: true, // this gives me require() function on the outside
  require: ['jquery']
}])

Do i need to bundle 'through' and 'duplexer' ? I've seen examples of that in browserify docs.

I can create two separate bundles in my gulp task, but i don't know how to access modules from one to the other.

like image 624
Elijah Avatar asked Nov 10 '22 13:11

Elijah


1 Answers

Reading about Webpack, I see where they solve so many questions including the one above. You can systematically externalize everything as shown in webpack's documentation. Snippet below:

  externals: [
    {
      a: false, // a is not external
      b: true, // b is external (require("b"))
      "./c": "c", // "./c" is external (require("c"))
      "./d": "var d" // "./d" is external (d)
    },
    // Every non-relative module is external
    // abc -> require("abc")
    /^[a-z\-0-9]+$/,
    function(context, request, callback) {
      // Every module prefixed with "global-" becomes external
      // "global-abc" -> abc
      if(/^global-/.test(request))
        return callback(null, "var " + request.substr(7));
      callback();
    },
    "./e" // "./e" is external (require("./e"))
  ]
like image 164
Elijah Avatar answered Nov 15 '22 09:11

Elijah