将html模板文件合并到一个JS文件中

vsy*_*ync 7 javascript underscore.js gulp underscore.js-templating

  1. 我有HTML模板文件(下划线模板语法)
  2. 这些文件以HTML格式保存,因此易于编辑(IDE语法高亮显示)
  3. 我不想用ajax获取它们,而是将它们全部组合起来并将它们作为js文件包含在内.
  4. 使用GULP作为我的任务运行器,我希望以某种方式将所有 HTML 组合成这样的东西,作为我可以包含在我的BUILD过程中的javascript文件:

template_file_name 是HTML文件名.

var templates = {
   template_file_name : '...template HTML string...',
   template_file_name2 : '...template HTML string...',
   template_file_name3 : '...template HTML string...'
}
Run Code Online (Sandbox Code Playgroud)

我真的不知道如何处理这个,以及如何从所有文件创建这样的文本..我可以将每个单独的文件转换为字符串,但我怎么能把它放在一个对象中?


更新 - 10月25日,15日 - ES6模块:

对于那些希望您的模板作为ES6模块的人,我创建了gulp-file-contents-to-modules

演示输出:

export var file_name = "This is bar.";
export var file_name2 = "This is foo.\r\n";
export var my-folder__file_name = "This is baz.\r\n";
Run Code Online (Sandbox Code Playgroud)

我的所有NPM包都与使用gulp组合模板文件有关:

  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

vsy*_*ync 2

我发现了这个很棒的工具,它完全可以满足我的需求:

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

用法(简单如)

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

然后您可以使用 访问键/值对象window.JST。这些值是函数(我不知道为什么,但就是这样)

更新 - 2015 年 8 月 21 日

我决定使用gulp-file-contents-to-json ,这是从文件内容生成 JSON 的最简单的方法。

更新 - 2016 年 7 月 19 日

我创建了 3 个 NPM 包(可能对某人有用):

  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