Module Code Recommendations - mitzerh/modulr-js GitHub Wiki
Accessing the Dependency Array
Typical:
Modulr.define("SitePackage:modules/foobar", ["jquery", "lodash", "OtherPackage:modules/foobar", "GlobalPackage:helper", "modernizr"], function($, _, foobar, helper, Modernizr){
// run stuff using the dependencies
$("body").addClass("foo");
if (Modernizr.svg) {
alert("svg available!");
}
console.log("from other package:", foobar);
console.log(_.indexOf([1, 2, 3, 4], 3));
helper.help();
});
Recommendation:
Modulr.define("SitePackage:modules/foobar", [
"require",
"jquery",
"lodash",
"OtherPackage:modules/foobar",
"modernizr",
"GlobalPackage:helper"
], function(require, $, _){
var foobar = require("OtherPackage:modules/foobar"),
Modernizr = require("modernizr"),
helper = require("GlobalPackage:helper");
// run stuff using the dependencies
$("body").addClass("foo");
if (Modernizr.svg) {
alert("svg available!");
}
console.log("from other package:", foobar);
console.log(_.indexOf([1, 2, 3, 4], 3));
helper.help();
});
Recommendations:
-
List the dependency array vertically instead of horizontally.
Ideal when a module has a lot of dependencies. It will be easy to keep track of all the dependencies
-
Take advantage of
require
to manage access to dependenciesWhen you have a long list of dependencies, it is hard to just rely on defining each dependency as an
argument
of yourfactory
. This is because you have to maintain the correct order of dependencies for your arguments. A common issue that remedies this way of access is when you have to move module dependencies around and you forgot to re-order the function arguments.With this recommendation, you should only define the arguments of the very most important dependencies that are most likely to not ever change. In this example, aside from
require
- arejquery
, andlodash
.
FAQ
Q: It takes up a lot of vertical space (sigh!)
A: If you have a minification process to your files, this is not a valid argument.
Q: Isn't it redundant and space consuming?
A: Minification is your friend. The headache it will save you is worth it!