combine html template files into one JS file

China☆狼群 提交于 2019-12-01 16:43:28

I've found this wonderful tool which does exactly what I want:

https://www.npmjs.org/package/gulp-template-compile

Usage (as simple as):

gulp.task('templates', function () {
    gulp.src('./views/templates/**/*.html')
        .pipe(template()) // converts html to JS
        .pipe(concat('templates.js'))
        .pipe(gulp.dest('./js/dist/'))
});

Then you can access the key/value object with window.JST. The values are functions (I don't know why, but it's like that)

Update - August 21, 2015

I've decided to use use gulp-file-contents-to-json which is the most simple thing possible for generating JSON from files' contents.

Update - July 19, 2016

I've created 3 NPM packages (might be handy to someone):

  1. https://www.npmjs.com/package/gulp-file-contents-to-keys
  2. https://www.npmjs.com/package/gulp-file-contents-to-modules
  3. https://www.npmjs.com/package/gulp-template-compile-es6

Another tool I just discovered for all handlebars.js users out there is gulp-handlebars.

https://www.npmjs.com/package/gulp-handlebars

https://github.com/lazd/gulp-handlebars

After adapting the sample gulp task to my needs I was able to include the template.js in my index.html and access every single template with a Handlebars wrapper via Template.[filename]().

e.g. Template.cart(data); returns the HTML string with all data filled in.

John Turingan

You can use https://www.npmjs.org/package/gulp-html-to-json.

It has a various feature and very easy to use. It will generate exactly what output you need.

var templates = {
   template_file_name : '...template HTML string...',
   template_file_name2 : '...template HTML string...',
   template_file_name3 : '...template HTML string...'
}

It also has angulartemplateCache generator if you use angularjs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!