gruntjs / grunt-contrib-jst

Compile underscore templates to JST file.
http://gruntjs.com/
MIT License
113 stars 45 forks source link

extend the amd option #59

Open alexus85 opened 9 years ago

alexus85 commented 9 years ago

It would be great if the option.amd was working similarly as in the grunt-contrib-handlebars (since it's very similar) This would enable users to define the library name right in the template init function..

gruntfile.json

amd:  ['my_underscore'],

jst.js

           if (typeof options.amd === 'boolean') {
                output.unshift("define(function(){");
           } else if (typeof options.amd === 'string') {
                output.unshift('define([\'' + options.amd + '\'], function(_) {');
           } else if (Array.isArray(options.amd)) {
            // convert options.amd to a string of dependencies for require([...])
            var amdString = '';
            for (var i = 0; i < options.amd.length; i++) {
                if (i !== 0) {
                    amdString += ', ';
                }

                amdString += '\'' + options.amd[i] + '\'';
            }
            output.unshift('define([' + amdString + '], function(_) {');
           }

result:

define(['my_underscore'], function(_) {

this["test"] = this["test"] || {};

this["test"]["test1"] = function(obj) {
var __t, __p = '', __e = _.escape;
__p += '<head><title>' +
((__t = ( obj.title )) == null ? '' : __t) +
'</title></head>';
return __p
};

  return this["test"];

});
jorrit commented 9 years ago

I think the _ part should be configurable too.

I propose a solution like this:

config

amd: {
  'underscore': '_'
}

code (untested)

var amdRequirements = [];
var amdImports = [];
_.each(options.amd, function(v, k) {
  amdRequirements.push(k);
  amdImports.push(v);
});

output.unshift('define(' + JSON.stringify(amdRequirements) + ', function(' + amdImports.join() + ') {')

result

define(['underscore'], function(_) {