Skip to content

Instantly share code, notes, and snippets.

@jensarps
Last active December 20, 2015 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jensarps/6062513 to your computer and use it in GitHub Desktop.
Save jensarps/6062513 to your computer and use it in GitHub Desktop.
Snippets from my post on creating dynamic/configurable builds with Grunt and Closure Compiler.
//configure closure compiler
var closureFiles = handlerClassNames.map(function (name) {
return 'src/' + name + '.js';
});
closureFiles.unshift('src/InputController.js');
closureFiles.push('build/bundle.js');
/* ... */
grunt.config.set('closure-compiler.bundle', {
closurePath: 'lib/closure',
jsOutputFile: 'build/input-controller.js',
js: closureFiles,
maxBuffer: 500,
options: closureOptions
});
grunt.task.run('closure-compiler:bundle');
'closure-compiler': {
all: {
closurePath: 'lib/closure',
jsOutputFile: 'build/build.js',
js: ['src/*.js'],
maxBuffer: 500,
options: {
'language_in': 'ECMASCRIPT5_STRICT',
'process_common_js_modules': null,
'transform_amd_modules': null,
'common_js_entry_module': '???'
}
}
}
// task configuration:
wrap: {
'all': {
src: ['build/input-controller.js'],
dest: './',
wrapper: [
UMDWrapper.before.join(''),
UMDWrapper.after.join('')
]
}
}
/* ... */
// later, as a last step of the configure task:
grunt.task.run('wrap:all');
// create bundle file contents
var bundleFileContents = [
'/*global define:false*/',
'/*jshint indent:false*/',
'define([',
'"../src/InputController",',
handlerModuleNames.join(',\n'),
'], function (InputController, ' + handlerClassNames.join(', ') + ') {',
'"use strict";',
'var bundle = new InputController();',
'bundle.registerDeviceHandlers([' + handlerClassNames.join(', ') + ']);',
'return bundle;',
'});\n'
].join('\n').replace(/"/g, '\'');
// write to disk
grunt.file.write('build/bundle.js', bundleFileContents);
grunt.registerTask('configure', 'A task to configure specific handlers', function () {
var handlerClassNames = [].slice.call(arguments).map(function (name) {
return name.slice(0, 1).toUpperCase() + name.slice(1, name.length) + 'Handler';
});
var handlerModuleNames = handlerClassNames.map(function (name) {
return '"../src/' + name + '"';
});
/* ... */
}
var handlers = grunt.option('handlers') || ('mouse,keyboard,gamepad,speech');
grunt.registerTask('default', ['configure:' + handlers.replace(/,/g, ':')]);
// define wrapper code
var exportName = 'inputController';
var UMDWrapper = {
before: [
'(function (name, definition, global) {',
'if (typeof define === "function") {',
'define(definition);',
'} else if (typeof module !== "undefined" && module.exports) {',
'module.exports = definition();',
'} else {',
'global[name] = definition();',
'}',
'})("' + exportName + '", function () {'
],
after: [
'return module$build$bundle; ',
'}, this);\n'
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment