Last active
December 21, 2015 06:18
-
-
Save ryan-blunden/6262744 to your computer and use it in GitHub Desktop.
Pre-compile your client-side underscore templates to individual AMD modules using Node.js.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Underscore Template AMD Compiler | |
Ryan Blunden | |
Licensed under the Apache License, Version 2.0 (the "License"); | |
you may not use this file except in compliance with the License. | |
You may obtain a copy of the License at | |
http://www.apache.org/licenses/LICENSE-2.0 | |
Unless required by applicable law or agreed to in writing, | |
software distributed under the License is distributed on an "AS | |
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | |
express or implied. See the License for the specific language | |
governing permissions and limitations under the License. | |
*/ | |
var fs = require('fs'); | |
var path = require('path'); | |
var _ = require('underscore'); | |
var TEMPLATE_EXT_REGEX = /\.(html|tmpl)$/; | |
var TEMPLATE_BASE_PATH = __dirname + '/PATH/TO/TEMPLATES/'; | |
/** | |
* Compile an underscore template source to an AMD module | |
* | |
* @param template {String} | |
* @returns {String} | |
*/ | |
function compileTemplateSourceToAMD(template) { | |
return 'define(function() { return ' + _.template(template).source.replace(/[\r\n\t]+/gm, '') + ' });'; | |
} | |
_.each(fs.readdirSync(TEMPLATE_BASE_PATH), function (file) { | |
if (!TEMPLATE_EXT_REGEX.test(file)) { | |
return; | |
} | |
var inputFile = TEMPLATE_BASE_PATH + path.sep + file; | |
var outputFile = TEMPLATE_BASE_PATH + path.sep + file.split('.').slice(0, -1) + '.js'; | |
fs.writeFileSync(outputFile, compileTemplateSourceToAMD(fs.readFileSync(inputFile).toString('utf-8'))); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment