Skip to content

Instantly share code, notes, and snippets.

@terinjokes
Created February 18, 2015 17:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terinjokes/9e95ea98d41919266fbb to your computer and use it in GitHub Desktop.
Save terinjokes/9e95ea98d41919266fbb to your computer and use it in GitHub Desktop.
Requiring a dynamically created file with Browserify
var Browserify = require('browserify');
var Readable = require('stream').Readable;
function stringStream(content) {
var s = new Readable();
s.push(content);
s.push(null);
return s;
}
var b = new Browserify();
/**
* Exclude any modules we dynamically generate from being resolved by `module-deps`.
*
* This can also be implemented by passing a function to Browserify's "filter" option,
* if you have a more complex scenario.
*
* ```
* var b = new Browserify({
* filter: function(id) {
* return id !== 'm1';
* }
* });
* ```
*/
b.exlcude('m1');
/**
* In addition to telling b.require what we want to expose this module as,
* give we can pass a filename that will be used when generating a source map
*/
b.require(stringStream('module.exports = 5'), {expose: 'm1', file: 'm1.js'});
b.add('./main.js');
b.bundle().pipe(process.stdout);
console.log(3 + require('m1'));
$ node build
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
console.log(3 + require('m1'));
},{"m1":"m1"}],"m1":[function(require,module,exports){
module.exports = 5
},{}]},{},["m1",1]);
$ node build | node
8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment