javascript - Handlebars.js 和 Webpack - 预编译模板

标签 javascript backbone.js handlebars.js webpack

我的网站使用 Backbone.jsHandlebars.jsWebpack。 我曾经使用 Require.js 而不是 Webpack。我有以下文件:

template.js

define({
    structure:      "structure.html",
    home:           "home.html"

});

webpack.config.js

resolve: {
        extensions: ['', '.js', '.json'],

        alias: {
            root: path.resolve( __dirname ),
            "router": path.resolve( __dirname ) + "/www/js/router",
            "templates": path.resolve( __dirname ) + "/www/js/templates",
            "handlebars": path.resolve( __dirname ) + "/node_modules/handlebars/dist/handlebars",
        "templates_html": path.resolve( __dirname ) + "/www/templates"
        }    
    },

view.js

define( ['jquery', 'underscore', 'backbone', "utils" ], 
       function($, _, Backbone, Utils) {

    var View = Utils.Page.extend({

        constructorName: "View",
        id: "home",

        initialize: function() {
            this.template = Utils.templates.home; // this is what I need

        },

        render: function () {
            this.$el.html(     this.template( this.model.toJSON() )    );
            return this;
        },

    });

    return View;

});

我想在我的网站开头使用 Handlebars.js 编译所有模板。 当我使用 Require.js 时,我习惯于做这样的事情:

utils.js

define( ['jquery', 'underscore', 'backbone', 'handlebars', 'templates'], 
       function($, _, Backbone, Handlebars, Templates) {

    var Utils = {
        templates: {}
    };

    for (var t in Templates) {
      Templates[t] = "text!" + Templates[t];
    }

    require(_.values(Templates), function() {

        var fragments = _.object(_.keys(Templates), arguments);

        // precompile all the fragments
        for (var t in fragments) {
          Utils.templates[t] = Handlebars.compile(fragments[t]); /* <Handlebars> */
        }

    });
    return Utils;
});

如何使用 webpackutils.js 中执行类似操作?

谢谢

最佳答案

您可以使用此 Handlebars 加载器进行网页包 https://github.com/pcardune/handlebars-loader/blob/master/README.md那里给出了完整的信息,但基本上设置加载器来编译模板文件夹中的所有 html 文件,或者将它们从 .html 重命名为 .hbs 或 .handlebars,然后简单地在模块中需要它们,它们就会被编译。

关于javascript - Handlebars.js 和 Webpack - 预编译模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37732807/

相关文章:

html - 在 .handlebars/html 中显示图像

javascript - 将项目添加到表格模板的 Handlebars

javascript - 使用 onClick 提交 PHP 表单

javascript - JavaScript 中处理大数(BigNum)的标准方案是什么?

javascript - Angular 4 - 如何从指令中运行动画?

javascript - 在不阻塞 UI 的情况下迭代数组的最佳方法

javascript - 使用 Backbone 和 Rails 实现加星收藏系统

node.js - Handlebars - 将内容从部分添加到 View 头部

javascript - 将 http 请求发送到第三方服务器并通过重定向获取响应

validation - 主干集合添加不会触发模型验证