Skip to content

Instantly share code, notes, and snippets.

@ptbrowne
Last active August 29, 2015 14:14
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 ptbrowne/2b5e9682698cdd5316f1 to your computer and use it in GitHub Desktop.
Save ptbrowne/2b5e9682698cdd5316f1 to your computer and use it in GitHub Desktop.
Reorder define
#! /usr/bin/env node
/*
This script is used to enforce a convention on the order
of the imports in a project that use requirejs
It will transform define calls dependency order according
to a priority.
Example:
```
define([
'views/1',
'models/2',
'views/3',
], function (
v1,
m2,
v3
) {
// BODY
});
```
with priority [ 'views', 'models' ] would be transformed into
```
define([
'views/1',
'views/3',
'models/2'
], function (
v1,
v3,
m2
) {
// BODY
})
```
Thanks to recast (https://github.com/benjamn/recast), the body is left untouched
*/
var recast = require('recast');
var _ = require('underscore');
var enumerate = function (arr) {
return _.map(arr, function (v,k) { return [k,v]; });
};
var getattr = function (k) {
return function (o) { return o[k]; };
};
var priority = function (priorities, name) {
var found = _.find(priorities, function (n) {
return new RegExp('^' + n[1]).test(name);
});
return found ? found[0] : Infinity;
};
var multiSort = function (arrs, fn) {
var zipped = _.zip.apply(_, arrs);
var sorted = _.sortBy(zipped, function (d) { return fn.apply(null, d); });
var unzipped = _.zip.apply(_, sorted);
return unzipped;
};
var priorities = enumerate([
'App',
'zepto',
'marionette',
'underscore',
'handlebars',
'backbone',
'moment',
'mapbox',
'views/',
'models/',
'collections/',
'text!templates',
'utils',
'configApp',
'helpers'
]);
var reorderDefine = function (node) {
var fn = node.arguments[1];
var arr = node.arguments[0];
var nbParams = fn.params.length;
if (!nbParams) {
return;
}
var named_deps = arr.elements.slice(0, nbParams);
var rest = arr.elements.slice(nbParams);
var sorter = _.compose(_.bind(priority, null, priorities), getattr('value'));
var sorted = multiSort([named_deps, fn.params], sorter);
arr.elements = sorted[0].concat(rest);
fn.params = sorted[1];
};
recast.run(function(ast, callback) {
recast.visit(ast, {
visitCallExpression: function(path) {
this.traverse(path);
var node = path.node;
if (node.callee.name == 'define') {
reorderDefine(node);
}
}
});
callback(ast);
}, {
reuseWhitespace: false
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment