Last active
June 15, 2016 06:22
-
-
Save fractalf/0be95add0b31b1448ee8c4df8204f601 to your computer and use it in GitHub Desktop.
A webpack loader for "JavaScript Templates" by blueimp that compiles templates to 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
/* | |
tmpl-loader.js | |
A webpack loader for "JavaScript Templates" by blueimp that compiles templates to js | |
https://github.com/blueimp/JavaScript-Templates#compiled-templates | |
This code is based on compile.js | |
Usage (webpack.config.js): | |
module.exports = { | |
module: { | |
loaders: [ | |
{ | |
test: /templates\.html$/, | |
loader: __dirname + '/tmpl-loader.js' | |
} | |
] | |
} | |
}; | |
MIT License http://www.opensource.org/licenses/mit-license.php | |
Author: Alf Marius Foss Olsen <alfm@rius.in> | |
*/ | |
"use strict"; | |
var fs = require('fs') | |
var tmpl = require('blueimp-tmpl'); | |
tmpl.print = function (str) { | |
// Only add helper functions if they are used inside of the template: | |
var helper = helperRegexp.test(str) ? tmpl.helper : '' | |
var body = str.replace(tmpl.regexp, tmpl.func) | |
if (helper || (/_e\s*\(/.test(body))) { | |
helper = '_e=tmpl.encode' + helper + ',' | |
} | |
return 'function(' + tmpl.arg + ',tmpl){' + | |
('var ' + helper + "_s='" + body + "';return _s;") | |
.split("_s+='';").join('') + '}' | |
} | |
// Retrieve the content of the minimal runtime: | |
var runtime = fs.readFileSync(__dirname + '/node_modules/blueimp-tmpl/js/runtime.js', 'utf8'); // EDIT! | |
// A regular expression to parse templates from script tags in a HTML page: | |
var regexp = /<script( id="([\w\-]+)")? type="text\/x-tmpl"( id="([\w\-]+)")?>([\s\S]+?)<\/script>/gi | |
// A regular expression to match the helper function names: | |
var helperRegexp = new RegExp( | |
tmpl.helper.match(/\w+(?=\s*=\s*function\s*\()/g).join('\\s*\\(|') + '\\s*\\(' | |
) | |
module.exports = function(source) { | |
this.cacheable && this.cacheable(); | |
let match, id, list = []; | |
while ((match = regexp.exec(source)) !== null) { | |
id = match[2] || match[4] | |
list.push("'" + id + "':" + tmpl.print(match[5])) | |
} | |
return runtime.replace('{}', '{' + list.join(',') + '}') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment