繁体   English   中英

ASP.NET捆绑和缩小并从其他Web应用程序使用它

[英]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的版本)

我不确定您可以将捆绑和缩小功能用作独立的实用程序,但可以尝试以下操作之一:

  1. 如果您已经在项目中使用捆绑和缩小功能,并且只想在浏览器中启动页面后输出JavaScript文件,则只需导航至文件的URL并下载即可。

要么

  1. 您可以研究诸如Springboard( https://github.com/soulwire/Springboard )或Grunt( http://gruntjs.com )之类的实用程序,尽管这两种方法都需要花费一些额外的工作才能在Windows上正常工作依赖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM