How can I precompile HandlebarsJS templates from Visual Studio?

走远了吗. 提交于 2020-01-11 19:38:20

问题


Is it possible to precompile Handlebars Templates from a postbuild event of Visual Studio or in the App_Start of a MVC web app? Thanks so much in advance. Dale


回答1:


Sure, you have many options:

  1. You can install node.js for windows and npm, and configure a post-build event to the compilation (example here from previous question)
  2. If you're using ember.js, here's an implementation that uses bundle transformation to achieve precompilation.
  3. Another for ember.js that supports components, here's the implementation, that also uses bundle transformation.
  4. Here is an example of compilation on C# using the Jurassic javascript compiler



回答2:


One way to do this is using bundle transform and the jurrasic js compiler to generate a js file with all your compiled views and partial views in it.

public class BundleConfig
{
    public static void RegisterHandlBarBundles(BundleCollection bundles, string path)
    {
        HandleBarBundleTransform transform = new HandleBarBundleTransform();
        transform.jsPath = path;
        bundles.Add(new Bundle("~/views.js", transform).IncludeDirectory("~/views", "*.hbs", true));
        BundleTable.EnableOptimizations = true;
    }
}

This has the benefit of not requiring node.js or ember while still using a simple bundletransform hook.

The full source for the HandleBarBundleTransform is here.

This has the convenience of the ember solution(s) @ahmed posted for those not using ember.




回答3:


I know this question was on Visual Studio 2010 but I found it when looking for a solution to Handlebars recompile in VS2013. I spent some time looking at solutions until I found that Web Essentials for Visual Studio added auto-precompile of handlebars templates in November 2014.

This feature in Web Essentials is not very well publicised and I only found it when I was building my solution and found that a .hbs.js file automatically appeared when I edited a handlebar .hbs file! I wasted a lot of time looking for solutions when it was already there.

I hope this answer helps someone else.



来源:https://stackoverflow.com/questions/16257849/how-can-i-precompile-handlebarsjs-templates-from-visual-studio

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