Created
February 12, 2015 21:11
-
-
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')`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: