問題描述
- 我有 HTML 模板文件(下劃線模板語法)
- 這些文件以 HTML 格式保存,因此易于編輯(IDE 語法突出顯示)
- 我不想用 ajax 來獲取它們,而是將它們全部組合起來,并將它們包含為
js
文件. - 使用 GULP 作為我的任務運行器,我希望它以某種方式結合所有 將 HTML 轉換成這樣的內容,作為一個 javascript 文件,我可以將其包含在我的 BUILD 過程中:
- I have HTML template files (underscore template syntax)
- These files are saved in HTML format so they would be easy to edit (IDE syntax highlight)
- I don't want to fetch them with ajax, but rather combine them all and include them as a
js
file. - Using GULP as my task-runner, I would like it to somehow combine all the HTML to something like this, as a javascript file that I could include in my BUILD process:
template_file_name
是 HTML 文件名.
template_file_name
is the HTML file name.
var templates = {
template_file_name : '...template HTML string...',
template_file_name2 : '...template HTML string...',
template_file_name3 : '...template HTML string...'
}
我真的不知道如何解決這個問題,以及如何從所有文件中創建這樣的文本.是的,我可以將每個單獨的文件轉換為字符串,但我怎樣才能將它放入對象中?
I don't really know how to approach this, and how to create such text from all the files..yes I can convert each individual file to a string, but how can I put it inside an object?
對于那些希望您的模板作為 ES6 模塊的人,我創建了 gulp-file-contents-to-modules
For those who want your templates as ES6 modules, I have created gulp-file-contents-to-modules
export var file_name = "This is bar.";
export var file_name2 = "This is foo.
";
export var my-folder__file_name = "This is baz.
";
我所有與使用 gulp 組合模板文件相關的 NPM 包:
- https://www.npmjs.com/package/gulp-file-contents-to-keys
- https://www.npmjs.com/package/gulp-file-contents-to-modules
- https://www.npmjs.com/package/gulp-template-compile-es6
推薦答案
我發現這個很棒的工具可以滿足我的需求:
I've found this wonderful tool which does exactly what I want:
https://www.npmjs.org/package/gulp-模板編譯
gulp.task('templates', function () {
gulp.src('./views/templates/**/*.html')
.pipe(template()) // converts html to JS
.pipe(concat('templates.js'))
.pipe(gulp.dest('./js/dist/'))
});
然后您可以使用 window.JST
訪問鍵/值對象.值是函數(我不知道為什么,但就是這樣)
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)
我決定使用 gulp-file-contents-to-json 這是從文件內容生成 JSON 的最簡單的方法.
I've decided to use use gulp-file-contents-to-json which is the most simple thing possible for generating JSON from files' contents.
我創建了 3 個 NPM 包(可能對某人很方便):
I've created 3 NPM packages (might be handy to someone):
- https://www.npmjs.com/package/gulp-file-contents-to-keys
- https://www.npmjs.com/package/gulp-file-contents-to-modules
- https://www.npmjs.com/package/gulp-template-compile-es6
這篇關于將html模板文件合并為一個JS文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!