template2module
precompile templates into modules, built for high performance
template2module vs underscore(jsperf)
install
# global $ npm install template2module -g# local $ npm install template2module --save-dev
usage
command line interface
$ template2module \ --engine <[underscore/dot/micro/anima]> \ --format <[amd/commonjs/esnext/umd]> \ --config <$path/to/config/file.js> \ $path/to/source/file
api interface
var tpl2mod = ; // render a underscore template into a modulevar underscoreEngine = tpl2modenginesunderscore;underscoreEngine;
customize
in case you need to render your template into a module that is in commonjs
format, and it has got some extra dependencies(zero-lang
, zero-text
, etc.), and you do not want to pass the helper
object as one of the arguments every time you use the module.
var tpl2mod = ;var templateEngine = ;var Engine = tpl2modEngine; var myAwesomeEngine = outerScopeVars: _e: true _p: true _s: true helper: true translate: true { return 'function (data, helper) {' ' data = data || {};' ' helper = helper || lang;' ' var _p = helper.print || function (s) {' ' return (s === null || s === undefined) ? '' : s;' ' };' ' var _e = helper.escape || _p;' ' return (function (' + dataformalArguments + ') {' datafunctionBody ' })(' + datarealArguments + ');' '}' ; } { return functionBody: ; } { // target moduleFormat is 'commonjs' only var resultStr = Engineprototyperender; // add extra dependencies in the rendered function return 'var lang = require("zero-lang");' 'var i18n = require("zero-locale");' 'var translate = i18n.translate;' '' + resultStr; }; myAwesomeEngine;
If you are using one of the supported engines, it would be much easier:
var tpl2mod = ;var underscoreEngine = tpl2modenginesunderscore;var Engine = tpl2modEngine; underscoreEngineouterScopeVarstranslate = true; // your extra helper function underscoreEngine { // target moduleFormat is 'commonjs' only var resultStr = Engineprototyperender; // add extra dependencies in the rendered function return 'var lang = require("zero-lang");' 'var i18n = require("zero-locale");' 'var translate = i18n.translate;' '' + resultStr;}; underscoreEngine;
design
module structure
// wrapping in amd/commonjs/esnext/umd format { // initializing return { // inner function body }dataarg1 dataarg2 .../* real arguments */; }
transform flow
supported template engines
- anima: animajs/template
- dot: doT.js
- micro: Microtemplating
- nano: trix/nano
- underscore: Underscore templates
and defining your own engine is SUPER EASY
supported modular formats
what's next
- use a move powerful AST analyzer (substack/node-falafel, etc.), to support more engines
- support more engines(pug, nunjucks, handlebar, jsrender, mustache, etc.)
- optimize module after rendered (google/closure-compiler, etc.)
- a friendly API interface
- toolkits: gulp task, webpack loader, grunt task, etc.