Automatically register dependencies

It's easy to forget to register a type in the application after you create it. Fortunately if you're using webpack or browserify we can automate the registration process.

browserify

You first need to install bulk-require and the bulkify transformation (Don't forget to add the transform to your browserify config).

npm install --save-dev bulk-require bulkify

Then all you need to do is call bulk-require from within your application

let { each } = require('lodash');
let bulk = require('bulk-require');

class Application extends Marty.Application {
  constructor(options) {
    super(options);

    let dependencies = bulk(__dirname, [
      'stores/*.js',
      'actions/*.js',
      'queries/*.js',
      'sources/*.js'
    ]);

    each(dependencies, dep => this.register(dep));
}

webpack

Thanks to webpack's dynamic require you don't need to install any dependencies. You just need to do this:

// Dynamically require in everything within the 'actions', 'queries', 'sources' and 'stores' folders
let context = require.context("./", true, /(actions|queries|sources|stores)/);

class Application extends Marty.Application {
  constructor(options) {
    super(options);

    // Iterate through all the JS files in those folders
    context.keys().forEach((key) =>  {
      if (!/\.js/.test(key)) {
        // Generate an Id based on directory structure.
        let id = key.replace('./', '').replace(/\//g, '.');

        this.register(id, context(key));
      }
    });
  }
}

module.exports = Application;