Skip to content

Instantly share code, notes, and snippets.

@mwcz
Created February 12, 2015 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwcz/67b29d767bd303a2cd86 to your computer and use it in GitHub Desktop.
Save mwcz/67b29d767bd303a2cd86 to your computer and use it in GitHub Desktop.
prefdep: apply dependencies to all RequireJS modules sharing a common prefix, for example, make 'angular-cookies' and 'angular-translate' depend on 'angular' with `prefdep('angular-', 'angular')`
/* global define, require */
define(['lodash'], function(_) {
'use strict';
function prefdep(prefix, parent_module) {
// grab a convenient reference to the requirejs config
var rjsconf = require.s.contexts._.config;
// create a shim entry, giving 'name' module a dependency on 'parent'
function create_shim(parent) {
return function (path, name) {
var newshim = {};
newshim[name] = {
deps: [parent]
};
return newshim;
};
}
// merge the new shim object from create_shim into the global requirejs
// config
function inject_shim(conf) {
return function (newshim) {
_.merge(conf.shim, newshim);
};
}
// if a module name begins with prefix, but isn't equal to prefix, call
// it a match. for example, if prefix is "angular", then
// "angular-ui-router" matches, but "angular" itself doesn't, since we
// want angular-ui-router to depend on angular, but we definitely don't
// want angular to depend on itself.
function dependson(parent) {
return function (path, name, object) {
return name !== parent && name.indexOf(parent) === 0;
};
}
// find the children of prefix
var babies = _.pick(rjsconf.paths, dependson(prefix));
// give each child a dependency on their parent
_.each(babies, _.compose(inject_shim(rjsconf), create_shim(parent_module)));
}
return prefdep;
});
@mwcz
Copy link
Author

mwcz commented Feb 12, 2015

Usage:

require(['prefdep'], function(prefdep) {
    prefdep('angular-', 'angular');
});

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