Compiling dynamically required modules with Browserify

Brad picture Brad · Feb 8, 2014 · Viewed 10.8k times · Source

I am using Browserify to compile a large Node.js application into a single file (using options --bare and --ignore-missing [to avoid troubles with lib-cov in Express]). I have some code to dynamically load modules based on what is available in a directory:

var fs = require('fs'),
    path = require('path');

fs.readdirSync(__dirname).forEach(function (file) {
    if (file !== 'index.js' && fs.statSync(path.join(__dirname, file)).isFile()) {
        module.exports[file.substring(0, file.length-3)] = require(path.join(__dirname, file));
    }
});

I'm getting strange errors in my application where aribtrary text files are being loaded from the directory my compiled file is loaded in. I think it's because paths are no longer set correctly, and because Browserify won't be able to require() the correct files that are dynamically loaded like this.

Short of making a static index.js file, is there a preferred method of dynamically requiring a directory of modules that is out-of-the-box compatible with Browserify?

Answer

mjlescano picture mjlescano · Dec 28, 2014

This plugin allows to require Glob patterns: require-globify

Then, with a little hack you can add all the files on compilation and not executing them:

// Hack to compile Glob files. Don´t call this function!
function ಠ_ಠ() {
  require('views/**/*.js', { glob: true })
}

And, for example, you could require and execute a specific file when you need it :D

var homePage = require('views/'+currentView)