Skip to content

Instantly share code, notes, and snippets.

@peller
Created October 4, 2013 21:59
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 peller/6833521 to your computer and use it in GitHub Desktop.
Save peller/6833521 to your computer and use it in GitHub Desktop.
Connect middleware to run the RequireJS optimizer
module.exports = function(baseUrl, optimize, fileList) {
var fileMap = {};
//probably should do a regexp match rather than pass in a list?
fileList.forEach(function (file) {
fileMap[file] = true;
});
var requireJS = require('requirejs');
return function(req, res, next) {
var file = fileMap[req.path];
if (!file) {
next();
return;
}
if (file.length) {
res.type('application/javascript').send(file);
return;
}
var requireJSConfig = {
baseUrl: baseUrl,
logLevel: 0,
name: req.path.slice(1, -3),
out: function(content) {
fileMap[req.path] = content;
res.type('application/javascript').send(content);
}
};
if (optimize) {
requireJSConfig.optimize = optimize;
}
requireJS.optimize(requireJSConfig, function() {
// result goes to 'out' function
}, function(err) {
next(err);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment