Skip to content

Instantly share code, notes, and snippets.

@jkrems
Last active December 31, 2015 11:59
Show Gist options
  • Save jkrems/7983003 to your computer and use it in GitHub Desktop.
Save jkrems/7983003 to your computer and use it in GitHub Desktop.
POC commonjs everywhere grunt task
'use strict';
var DESC = 'Generate bundle from commonjs-everywhere';
var escodegenFormat = {
indent: {
style: ' ',
base: 0
},
renumber: true,
hexadecimal: true,
quotes: 'auto',
parentheses: false
};
module.exports = function(grunt) {
var cjsify = require('commonjs-everywhere').cjsify;
var escodegen = require('escodegen');
var path = require('path');
grunt.registerTask('cjsify', DESC, function() {
var options = this.options();
var rawFiles = grunt.config([this.name]),
files = grunt.task.normalizeMultiTaskFiles(rawFiles);
function makeAbsolute(filename) {
if (filename) {
return path.resolve(filename);
}
return filename;
}
options.root = makeAbsolute(options.root);
return files.every(function(f) {
var src = f.src, dest = f.dest, bundled, out, map, code, filename, sourceMapItem;
if (src.length !== 1) {
grunt.log.error('Not exactly one source file: ' + src.join(', '));
return false;
}
src = makeAbsolute(src[0]);
grunt.log.subhead('Generating ' + dest + ' from ' + src);
bundled = cjsify(src, options.root, options);
out = escodegen.generate(bundled, {
comment: !options.minify,
sourceMap: true,
sourceMapWithCode: true,
sourceMapRoot: options.sourceMap != null ? path.relative(path.dirname(options.sourceMap), root) : '.',
format: options.minify ? escodegen.FORMAT_MINIFY : escodegenFormat
});
map = out.map, code = out.code;
if ((options.sourceMap || options.inlineSourceMap) && options.inlineSources) {
for (filename in processed) {
if (!processed.hasOwnProperty(filename)) continue;
sourceMapItem = processed[filename];
map.setSourceContent(sourceMapItem.canonicalName, sourceMapItem.fileContents);
}
}
if (options.sourceMap) {
grunt.file.write(options.sourceMap, '' + map);
sourceMappingUrl =
options.output ?
path.relative(path.dirname(options.output), options.sourceMap)
: options.sourceMap;
if (!options.inlineSourceMap) {
code = code + "\n//# sourceMappingURL=" + sourceMappingUrl;
}
}
if (options.inlineSourceMap) {
code = (
code +
'\n//# sourceMappingURL=' +
'data:application/json;charset=utf-8;base64,' + new Buffer('' + map, 'utf-8').toString('base64') + '\n'
);
}
grunt.file.write(dest, code);
return true;
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment