Skip to content Skip to sidebar Skip to footer

Compiling Dynamically Required Modules With Browserify

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 som

Solution 1:

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)

Solution 2:

Browserify does not support dynamic requires - see GH issue 377.

The only method for dynamically requiring a directory I am aware of: a build step to list the directory files and write the "static" index.js file.


Solution 3:

There's also the bulkify transform, as documented here:

https://github.com/chrisdavies/tech-thoughts/blob/master/browserify-include-directory.md

Basically, you can do this in your app.js or whatever:

var bulk = require('bulk-require');

// Require all of the scripts in the controllers directory
bulk(__dirname, ['controllers/**/*.js']);

And my gulpfile has something like this in it:

gulp.task('js', function () {
  return gulp.src('./src/js/init.js')
    .pipe(browserify({
      transform: ['bulkify']
    }))
    .pipe(rename('app.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dest/js'));
});

Post a Comment for "Compiling Dynamically Required Modules With Browserify"