Handlebars.js 和 Webpack - 预编译模板

Handlebars.js and Webpack - precompile templates

我正在为我的网站使用 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;
});

如何在 utils.js 中用 webpack 做类似的事情?

谢谢

您可以将此 handlebars 加载器用于 web pack https://github.com/pcardune/handlebars-loader/blob/master/README.md 此处提供了完整信息,但基本上将加载器设置为编译模板文件夹中的所有 html 文件或将它们重命名为 .html 到 .hbs 或 .handlebars 然后在你的模块中简单地要求它们,它们将被编译。