[英]ASP.NET Bundling and Minification and using it from other web application
我有ASP.NET MVC 4應用程序,其中包含一些簡單的jQuery小部件的庫。 現在,我想允許其他Web應用程序使用該庫。 與其在客戶端頁面上逐個文件插入每個小部件文件,不如在一個請求中將它們全部打包為一個包,這將是一個很好的選擇。 有人知道可以使用Microsoft ASP.NET Web優化框架進行捆綁嗎? 換句話說,我想准備一些“ jquery-library-1.0.0.js”文件並允許其他應用程序加載它。
我所能找到的就是如何在MVC應用程序中使用它,而沒有關於如何使用靜態名稱准備捆綁軟件的內容。
經過一些研究,我找到了執行此操作的方法-使用IBundleTransform接口。 它允許訪問包內容,我只需要將其轉儲到我想要的位置的磁盤中,以后就可以將其用於任何其他想要使用該庫的應用程序中。
public class ScriptsBundleTransform : IBundleTransform
{
public string ScriptsPath { get; set; }
public string Version { get; set; }
public string Minified { get; set; }
public string Full { get; set; }
public ScriptsBundleTransform()
{
}
public ScriptsBundleTransform(string path, string version, string minified, string full)
{
ScriptsPath = path;
Version = version;
Minified = minified;
Full = full;
}
public void Process(BundleContext context, BundleResponse response)
{
string scriptsRoot = context.HttpContext.Server.MapPath(Path.Combine(ScriptsPath, Version));
if (!Directory.Exists(scriptsRoot))
Directory.CreateDirectory(scriptsRoot);
// if minified file name specified...
if (!string.IsNullOrEmpty(Minified))
{
using (TextWriter writer = File.CreateText(Path.Combine(scriptsRoot, Minified)))
{
writer.Write(response.Content);
}
}
// if full file name specified...
if (!string.IsNullOrEmpty(Full))
{
using (Stream writer = File.OpenWrite(Path.Combine(scriptsRoot, Full)))
{
foreach (var file in response.Files)
{
file.VirtualFile.Open().CopyTo(writer);
}
}
}
}
}
然后,我只需要在bundle config中將此轉換器添加到要轉儲到磁盤的bundle中:
widgets.Transforms.Add(new ScriptsBundleTransform()
{
Version = "1.0.0",
ScriptsPath = "~/Scripts",
Minified = "jquery.library.min.js",
Full = "jquery.library.js"
});
即使庫中的任何小部件將被更改,轉儲文件也將自動重新生成,而我沒有手動控制此過程。
捆綁和縮小是Asp.Net 4.5的新功能
您可以在此處找到更多詳細信息: http : //www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
因此,如果您擁有Asp.Net 4.5,則可以立即使用捆綁和縮小功能。 (您尚未指定您的應用程序所基於的Asp.Net的版本)
我不確定您可以將捆綁和縮小功能用作獨立的實用程序,但可以嘗試以下操作之一:
要么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.