2014-01-15 39 views
1

我在我们的基于MVC的解决方案中加入了一个大的JavaScript应用程序。但是,该应用程序包含大量文件,因此我希望对其进行捆绑和缩小。实际上,我希望在所有第三方javascript和CSS文件上启用捆绑功能,同时保持我们自己开发的文件未被分类和解包。当然,直到发布。在第三方库上启用捆绑和缩小功能

有办法使全局优化:

public static void RegisterBundles(BundleCollection bundles) 
{ 
    Bundle ckScripts = new ScriptBundle("~/scripts/ckeditor") 
     .IncludeDirectory("~/Areas/CMS/Editor", "*.js", true); 
    bundles.Add(ckScripts); 
    BundleTable.EnableOptimizations = true; 
} 

然而,这种情况发生在在束表内的所有束顶端BundleTable级启用优化。

我需要有这样的事情:

public static void RegisterBundles(BundleCollection bundles) 
{ 
    Bundle ckScripts = new ScriptBundle("~/scripts/ckeditor") 
     .IncludeDirectory("~/Areas/CMS/Editor", "*.js", true) 
     .EnableOptimizations(); 
    bundles.Add(ckScripts); 
} 

这将有效地使优化只对特定的捆绑。

我知道,目前没有Bundle.EnableOptimizations()方法,并且创建了这样的事实,即优化发生在BundleTable级别,这种固有的全局设计,创建这样的方法,将证明是非常困难的。

所以,在这里我失去了想法在哪里看。

问题:

  1. 有没有什么地方可替代的框架,支持此
  2. 是否有一个的contrib项目的地方,将提供此
  3. 你有没有遇到过这样的需要,可能有一个解决方案
  4. 假设没有现有的解决方案,请发布一个想法如何开始解决这个挑战。

从我所知道的BundleTable是一个单身人士。这意味着只能有一个实例。我有一个创建另一个捆绑表的想法,但当我开始研究如何让MVC使用它时,我迷失了方向。

另一个起点是编写自定义渲染器。一个模仿System.Web.Optimization.Scripts.Render()的行为,但我再一次迷失在试图弄清BundleTable进入图片的状态。


UPDATE


好像我可以通过使用HtmlHelper创建一个新的的BundleContextBundleResponse

public static IHtmlString RenderBundled<TSource>(this HtmlHelper<TSource> helper, string bundlePath) 
{ 
    // Find the bundle in question 
    var bundle = BundleTable.Bundles.FirstOrDefault(b => b.Path == bundlePath); 

    // No bundle found, return 
    if (bundle == null) return MvcHtmlString.Create(String.Empty); 

    // Add the bundle found into a new collection 
    BundleCollection coll = new BundleCollection {bundle}; 

    // Create a new BundleContext 
    BundleContext ctx = new BundleContext(helper.ViewContext.HttpContext, coll, "~/bundles"); 

    // Enable optimizations 
    ctx.EnableOptimizations = true; 

    // Create the response (this contains bundled & minified script/styles from bundle) 
    BundleResponse response = bundle.GenerateBundleResponse(ctx); 

    // Render the content based on ContentType 
    if (response.ContentType == "text/css") 
     return RenderStyle(response.Content);// returns <style>bundled content</style> 

    if (response.ContentType == "text/javascript") 
     return RenderScript(response.Content); // returns <script>bundled content</script> 

    // In any other case return "nothing" 
    return MvcHtmlString.Create(String.Empty); 
} 

这可能不是最好的办法。从每个页面请求创建BundleContext开销,并将脚本/样式有效负载添加到页面输出中,而无需缓存功能。但这是一个开始。我注意到的一件事是捆绑的内容实际上将被缓存在HttpContext.Cache中。因此,理论上我可以将bundle path分成script srcstyle href,然后以某种方式处理来自服务器端的请求。

回答