Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

How to include a file in bundle dynamically #376

outbounder opened this Issue Apr 10, 2013 · 1 comment


None yet
1 participant

Hi @substack

I've been playing with browserify lately and happened to find it quite hard to just include a file in given bundle dynamically.

Here is what I'm trying to achieve (may be you could give me some hints on what I'm doing wrong):

  1. having a file "test.js" with the following contents:
var compile = function(path){
  return require(path);
var template = compile("./t1.template");
  1. attaching a listener on bundle.on('file' ...); and re-parse the test.js file contents to find out that there is compile("./t1.template") and to grab the actual full file path to be required.

  2. I use bundle.require(templatePath) within bundle.on('file',...)'s callback but sadly browserfiy falls into infinitive loop. :(

Here is the test code (I'm using "browserify": "2.12.0")

bundle.on("file", function(file){
  if (!/\.js/.test(file)) return;

  var buffer = fs.readFileSync(file).toString();
  var includeIndex = buffer.indexOf("compile(");
  var endOfInclude = buffer.indexOf(");", includeIndex);
  if(includeIndex !== -1) {
    var toInclude = buffer.substring(includeIndex+9, endOfInclude-1);
    var templateFile = path.join(path.dirname(file), toInclude);

I would like to include the found templates within the bundle dynamically so that when browser-side js executes it can require them as normal.

Please note that I'm having already a transformer defined for including files with .template extension, here is its code if it could be the problem (which I doubt):

  if (!/\.template/.test(file)) return through();

  var buffer = "";

  return through(function(chunk) {
    buffer += chunk.toString();
  function() {
    var compiled = "module.exports = '" + JSON.stringify(buffer.toString()) + "'\n";

never mind I've found a workaround solution.

@outbounder outbounder closed this Apr 12, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment