browserify-compile-templates
Compiles underscore templates from HTML script tags into CommonJS in a browserify transform. You can add multiple script tags to each file. Requiring the file will return an object with a property for each script tag. The ID attribute is the key and the compiled template function as the value.
See the underscore documentation for more details.
Usage
Install
npm install --save-dev browserify-compile-templates
Create a template file
myTemplates.html
Use the id
attribute to identify the template from your JS source.
Use data-variable-name to change the variable name that is used in the underscore template. obj
is the default
Transform options
Note: This will affect the compilation of all your templates!
Alternatively, if you do not want to scope your template values under a variable, provide the { noVar: true }
option to the transform.
If you do not want to require underscore library inside compiled script provide the the { globalUnderscore: true }
option to the transform.
Require the template file
A JS file
var $ = ;var templates = ; ;;
Add to browserify
Register the template and tell browserify to look for html extensions
browserify -t browserify-compile-templates --extension=.html
Why?
The advantage of this transform over other transforms or plugins is that the templates are backwards compatible with non-browserified code. Template files formatted this way can also be included directly in HTML. A UMD module that is shared in both a browserified and non-browserified codebase can be used like this:
{ if typeof module !== 'undefined' // CommonJS - templates are precompiled and bundled in with JS var templates = ; ; else // Borwser globals. Templates are included in html and need to be compiled client-side var $template1 = ; var $tempalte2 = ;
The commonJS environment gets the benefit of the precompiled template. Other environments can still include the file on the page and access it by ID.