C# 即时或在构建时连接和缩小 JavaScript - ASP.NET MVC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/890561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate and minify JavaScript on the fly OR at build time - ASP.NET MVC
提问by Charlino
As an extension to this question here Linking JavaScript Libraries in User ControlsI was after some examples of how people are concatenating and minifying JavaScript on the fly OR at build time. I would also like to see how it then works into your master pages.
作为这里链接用户控件中的 JavaScript 库的这个问题的扩展,我是在一些关于人们如何在运行中或在构建时连接和缩小 JavaScript 的示例之后。我还想看看它是如何在您的母版页中工作的。
I don't mind page specific files being minified and linked inidividually as they currently are (see below) but all the JavaScript files on the main master page (I have about 5 or 6) I would like concatenated and minified.
我不介意页面特定文件被缩小和单独链接,因为它们目前(见下文)但主母版页上的所有 JavaScript 文件(我有大约 5 或 6 个)我想连接和缩小。
Bonus points for anyone who also incorporates CSS concatenation and minification! :-)
任何人也结合 CSS 串联和缩小的奖励积分!:-)
Current master page with the common JavaScript files that I would like concatenated and minified:
当前母版页包含我想要连接和缩小的常见 JavaScript 文件:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<head runat="server">
... BLAH ...
<asp:ContentPlaceHolder ID="AdditionalHead" runat="server" />
... BLAH ...
<%= Html.CSSBlock("/styles/site.css") %>
<%= Html.CSSBlock("/styles/jquery-ui-1.7.1.css") %>
<%= Html.CSSBlock("/styles/jquery.lightbox-0.5.css") %>
<%= Html.CSSBlock("/styles/ie6.css", 6) %>
<%= Html.CSSBlock("/styles/ie7.css", 7) %>
<asp:ContentPlaceHolder ID="AdditionalCSS" runat="server" />
</head>
<body>
... BLAH ...
<%= Html.JSBlock("/scripts/jquery-1.3.2.js", "/scripts/jquery-1.3.2.min.js") %>
<%= Html.JSBlock("/scripts/jquery-ui-1.7.1.js", "/scripts/jquery-ui-1.7.1.min.js") %>
<%= Html.JSBlock("/scripts/jquery.validate.js", "/scripts/jquery.validate.min.js") %>
<%= Html.JSBlock("/scripts/jquery.lightbox-0.5.js", "/scripts/jquery.lightbox-0.5.min.js") %>
<%= Html.JSBlock("/scripts/global.js", "/scripts/global.min.js") %>
<asp:ContentPlaceHolder ID="AdditionalJS" runat="server" />
</body>
Used in a page like this (which I'm happy with):
在这样的页面中使用(我很满意):
<asp:Content ID="signUpContent" ContentPlaceHolderID="AdditionalJS" runat="server">
<%= Html.JSBlock("/scripts/pages/account.signup.js", "/scripts/pages/account.signup.min.js") %>
</asp:Content>
UPDATE:Recommendations for now (late 2013):
更新:目前的建议(2013 年末):
I would look at Microsoft ASP.NET's built in Bundling and Minification.
我会看看 Microsoft ASP.NET 内置的Bundling 和 Minification。
采纳答案by RedWolves
In the appendix of Professional ASP.NET 3.5Scott Hanselman talks about Packer for .NET. This will integrate with MSBuild and pack javascript files for production deployments etc.
在Professional ASP.NET 3.5的附录中,Scott Hanselman 谈到了Packer for .NET。这将与 MSBuild 集成并为生产部署等打包 javascript 文件。
回答by Scott Hanselman
Why not use the ScriptManager? Here's an MVCScriptManagerthat will combine AND squish.
为什么不使用 ScriptManager?这是一个MVCScriptManager,它将结合 AND 挤压。
回答by Bryan Migliorisi
Use either YUI Compressor or Dojo compressor. They both use the Rhino JS parsing engine which tokenizes your code, and will therefore only work if the code is valid code. If there is an error, they'll let you know (which is a nice bonus IMO!) Packer on the other hand, will pack your code even if it contains errors.
使用 YUI Compressor 或 Dojo 压缩器。它们都使用 Rhino JS 解析引擎来标记您的代码,因此只有在代码是有效代码时才会起作用。如果有错误,他们会通知您(这是 IMO 的一个很好的奖励!)另一方面,Packer 会打包您的代码,即使它包含错误。
I use YUI in all my projects via build scripts. Never do it on the fly, it takes too long to do the compression. Both YUI and Dojo are Java based (ala Rhino) and if you do it on the fly, you'll be spawning background processes to generate the output - not good for performance. Always do it at build time.
我通过构建脚本在所有项目中使用 YUI。永远不要在飞行中进行,进行压缩需要很长时间。YUI 和 Dojo 都是基于 Java 的(ala Rhino),如果您在运行时这样做,您将产生后台进程来生成输出 - 不利于性能。始终在构建时进行。
回答by travis
Here's what I've used for concatenating, compressing and caching CSS and JS files: http://gist.github.com/130913
这是我用于连接、压缩和缓存 CSS 和 JS 文件的内容:http: //gist.github.com/130913
It just requires Yahoo.Yui.Compressor.dll in the bin directory. It doesn't compress at compile time, but the files are cached with a file dependency, so they are only loaded once, until they're changed.
它只需要 bin 目录中的 Yahoo.Yui.Compressor.dll。它不会在编译时压缩,但文件会与文件依赖项一起缓存,因此它们只会加载一次,直到它们被更改。
Then I just add this code in the <head>:
然后我只需在 <head> 中添加此代码:
<link rel="stylesheet" type="text/css" href="/YuiCompressor.ashx?css=reset,style,etc" />
and this just before the </body>:
就在 </body> 之前:
<script type="text/javascript" src="/YuiCompressor.ashx?js=main,other,etc"></script>
It's designed to work with multiple files all in the same path but could easily be upgraded to support different paths.
它旨在处理同一路径中的多个文件,但可以轻松升级以支持不同的路径。
回答by Mark Gibaud
Try this:
尝试这个:
I've recently completed a fair bit of research and consequent development at work that goes quite far to improve the performance of our web application's front-end. I thought I'd share the basic solution here.
我最近在工作中完成了相当多的研究和后续开发,这些工作对提高我们的 Web 应用程序前端的性能大有帮助。我想我会在这里分享基本的解决方案。
The first obvious thing to do is benchmark your site using Yahoo's YSlow and Google's PageSpeed. These will highlight the "low-hanging fruit" performance improvements to make. Unless you've already done so, the resulting suggestions will almost certainly include combining, minifying and gzipping your static content.
第一个显而易见的事情是使用雅虎的 YSlow 和谷歌的 PageSpeed 对您的网站进行基准测试。这些将突出“唾手可得”的性能改进。除非您已经这样做了,否则产生的建议几乎肯定会包括合并、缩小和压缩静态内容。
The steps we're going to perform are:
我们要执行的步骤是:
Write a custom HTTPHandler to combine and minify CSS. Write a custom HTTPHandler to combine and minify JS. Include a mechanism to ensure that the above only do their magic when the application is not in debug mode. Write a custom server-side web control to easily maintain css/js file inclusion. Enable GZIP of certain content types on IIS 6. Right, let's start with CSSHandler.asax that implements the .NET IHttpHandler interface:
编写自定义 HTTPHandler 来组合和缩小 CSS。编写一个自定义的 HTTPHandler 来组合和缩小 JS。包括一种机制,以确保上述内容仅在应用程序未处于调试模式时发挥作用。编写自定义的服务器端 Web 控件以轻松维护 css/js 文件包含。在 IIS 6 上启用某些内容类型的 GZIP。好吧,让我们从实现 .NET IHttpHandler 接口的 CSSHandler.asax 开始:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
namespace WebApplication1
{
public class CssHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
string[] cssFiles = context.Request.QueryString["cssfiles"].Split(',');
List<string> files = new List<string>();
StringBuilder response = new StringBuilder();
foreach (string cssFile in cssFiles)
{
if (!cssFile.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
{
//log custom exception
context.Response.StatusCode = 403;
return;
}
try
{
string filePath = context.Server.MapPath(cssFile);
string css = File.ReadAllText(filePath);
string compressedCss = Yahoo.Yui.Compressor.CssCompressor.Compress(css);
response.Append(compressedCss);
}
catch (Exception ex)
{
//log exception
context.Response.StatusCode = 500;
return;
}
}
context.Response.Write(response.ToString());
string version = "1.0"; //your dynamic version number
context.Response.ContentType = "text/css";
context.Response.AddFileDependencies(files.ToArray());
HttpCachePolicy cache = context.Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.VaryByParams["cssfiles"] = true;
cache.SetETag(version);
cache.SetLastModifiedFromFileDependencies();
cache.SetMaxAge(TimeSpan.FromDays(14));
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
}
}
}
Ok, now some explanation:
好的,现在解释一下:
IsReUsable property:
IsReUsable 属性:
We aren't dealing with anything instance-specific, which means we can safely reuse the same instance of the handler to deal with multiple requests, because our ProcessRequest is threadsafe. More info.
我们不处理任何特定于实例的事情,这意味着我们可以安全地重用处理程序的同一个实例来处理多个请求,因为我们的 ProcessRequest 是线程安全的。更多信息。
ProcessRequest method:
处理请求方法:
Nothing too hectic going on here. We're looping through the CSS files given to us (see the CSSControl below for how they're coming in) and compressing each one, using a .NET port of Yahoo's YUICompressor, before adding the contents to the outgoing response stream.
这里没有什么太忙乱的事情。在将内容添加到传出响应流之前,我们正在循环浏览提供给我们的 CSS 文件(请参阅下面的 CSSControl,了解它们是如何传入的)并使用 Yahoo 的 YUICompressor 的 .NET 端口压缩每个文件。
The remainder of the method deals with setting up some HTTP caching properties to further optimise the way the browser client downloads (or not, as the case may be) content.
该方法的其余部分涉及设置一些 HTTP 缓存属性,以进一步优化浏览器客户端下载(或不下载,视情况而定)内容的方式。
We set Etags in code so that they may be the same across all machines in our server farm. We set Response and Cache dependencies on our actual files so, should they be replaced, cache will be invalidated. We set Cacheability such that proxies can cache. We VaryByParams using our cssfiles attribute, so that we can cache per CSS file group submitted through the handler. And here is the CSSControl, a custom server-side control inheriting the .NET LiteralControl.
我们在代码中设置 Etags,以便它们在我们服务器群中的所有机器上都相同。我们在实际文件上设置了响应和缓存依赖项,因此,如果它们被替换,缓存将失效。我们设置 Cacheability 以便代理可以缓存。我们使用我们的 cssfiles 属性 VaryByParams,以便我们可以缓存通过处理程序提交的每个 CSS 文件组。这里是 CSSControl,一个自定义的服务器端控件,继承了 .NET LiteralControl。
Front:
正面:
<customcontrols:csscontrol id="cssControl" runat="server">
<CustomControls:Stylesheet File="main.css" />
<CustomControls:Stylesheet File="layout.css" />
<CustomControls:Stylesheet File="formatting.css" />
</customcontrols:csscontrol>
Back:
后退:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Linq;
using TTC.iTropics.Utilities;
namespace WebApplication1
{
[DefaultProperty("Stylesheets")]
[ParseChildren(true, "Stylesheets")]
public class CssControl : LiteralControl
{
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public List<Stylesheet> Stylesheets { get; set; }
public CssControl()
{
Stylesheets = new List<Stylesheet>();
}
protected override void Render(HtmlTextWriter output)
{
if (HttpContext.Current.IsDebuggingEnabled)
{
const string format = "<link rel=\"Stylesheet\" href=\"stylesheets/{0}\"></link>";
foreach (Stylesheet sheet in Stylesheets)
output.Write(format, sheet.File);
}
else
{
const string format = "<link type=\"text/css\" rel=\"Stylesheet\" href=\"stylesheets/CssHandler.ashx?cssfiles={0}&version={1}\"/>";
IEnumerable<string> stylesheetsArray = Stylesheets.Select(s => s.File);
string stylesheets = String.Join(",", stylesheetsArray.ToArray());
string version = "1.00" //your version number
output.Write(format, stylesheets, version);
}
}
}
public class Stylesheet
{
public string File { get; set; }
}
}
HttpContext.Current.IsDebuggingEnabled is hooked up to the following setting in your web.config:
HttpContext.Current.IsDebuggingEnabled 与 web.config 中的以下设置相关联:
<system.web>
<compilation debug="false">
</system.web>
So, basically, if your site is in debug mode you get HTML markup like this:
因此,基本上,如果您的站点处于调试模式,您会得到如下 HTML 标记:
<link rel="Stylesheet" href="stylesheets/formatting.css"></link>
<link rel="Stylesheet" href="stylesheets/layout.css"></link
<link rel="Stylesheet" href="stylesheets/main.css"></link>
But if you're in production mode (debug=false), you'll get markup like this:
但如果您处于生产模式 (debug=false),您将获得如下标记:
<link type="text/css" rel="Stylesheet" href="CssHandler.ashx?cssfiles=main.css,layout.css,formatting.css&version=1.0"/>
The latter will then obviously invoke the CSSHandler, which will take care of combining, minifying and cache-readying your static CSS content.
后者显然会调用 CSSHandler,它将负责组合、缩小和缓存静态 CSS 内容。
All of the above can then also be duplicated for your static JavaScript content:
然后也可以为您的静态 JavaScript 内容复制上述所有内容:
`JSHandler.ashx:
`JSHandler.ashx:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
namespace WebApplication1
{
public class JSHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
string[] jsFiles = context.Request.QueryString["jsfiles"].Split(',');
List<string> files = new List<string>();
StringBuilder response = new StringBuilder();
foreach (string jsFile in jsFiles)
{
if (!jsFile.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
{
//log custom exception
context.Response.StatusCode = 403;
return;
}
try
{
string filePath = context.Server.MapPath(jsFile);
files.Add(filePath);
string js = File.ReadAllText(filePath);
string compressedJS = Yahoo.Yui.Compressor.JavaScriptCompressor.Compress(js);
response.Append(compressedJS);
}
catch (Exception ex)
{
//log exception
context.Response.StatusCode = 500;
return;
}
}
context.Response.Write(response.ToString());
string version = "1.0"; //your dynamic version number here
context.Response.ContentType = "application/javascript";
context.Response.AddFileDependencies(files.ToArray());
HttpCachePolicy cache = context.Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.VaryByParams["jsfiles"] = true;
cache.VaryByParams["version"] = true;
cache.SetETag(version);
cache.SetLastModifiedFromFileDependencies();
cache.SetMaxAge(TimeSpan.FromDays(14));
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
}
}
}
And its accompanying JSControl:
及其附带的 JSControl:
Front:
正面:
<customcontrols:JSControl ID="jsControl" runat="server">
<customcontrols:Script File="jquery/jquery-1.3.2.js" />
<customcontrols:Script File="main.js" />
<customcontrols:Script File="creditcardpayments.js" />
</customcontrols:JSControl>
Back:
后退:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Linq;
namespace WebApplication1
{
[DefaultProperty("Scripts")]
[ParseChildren(true, "Scripts")]
public class JSControl : LiteralControl
{
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public List<Script> Scripts { get; set; }
public JSControl()
{
Scripts = new List<Script>();
}
protected override void Render(HtmlTextWriter writer)
{
if (HttpContext.Current.IsDebuggingEnabled)
{
const string format = "<script src=\"scripts\{0}\"></script>";
foreach (Script script in Scripts)
writer.Write(format, script.File);
}
else
{
IEnumerable<string> scriptsArray = Scripts.Select(s => s.File);
string scripts = String.Join(",", scriptsArray.ToArray());
string version = "1.0" //your dynamic version number
const string format = "<script src=\"scripts/JsHandler.ashx?jsfiles={0}&version={1}\"></script>";
writer.Write(format, scripts, version);
}
}
}
public class Script
{
public string File { get; set; }
}
}
Enabling GZIP:
启用 GZIP:
As Jeff Atwood says, enabling Gzip on your web site server is a no-brainer. After some tracing, I decided to enable Gzip on the following file types:
正如 Jeff Atwood 所说,在您的网站服务器上启用 Gzip 是轻而易举的事。经过一些跟踪,我决定对以下文件类型启用 Gzip:
.css .js .axd (Microsoft Javascript files) .aspx (Usual ASP.NET Web Forms content) .ashx (Our handlers) To enable HTTP Compression on your IIS 6.0 web server:
.css .js .axd(Microsoft Javascript 文件) .aspx(通常的 ASP.NET Web 表单内容) .ashx(我们的处理程序) 在 IIS 6.0 Web 服务器上启用 HTTP 压缩:
Open IIS, Right click Web Sites, Services tab, enable Compress Application Files and Compress Static Files Stop IIS Open up IIS Metabase in Notepad (C:\WINDOWS\system32\inetsrv\MetaBase.xml) – and make a back up if you're nervous about these things Locate and overwrite the two IIsCompressionScheme and one IIsCompressionSchemes elements with the following:
打开 IIS,右键单击网站,服务选项卡,启用压缩应用程序文件和压缩静态文件 停止 IIS 在记事本中打开 IIS 元数据库 (C:\WINDOWS\system32\inetsrv\MetaBase.xml) – 如果您愿意,请进行备份对这些事情感到紧张使用以下内容定位并覆盖两个 IIsCompressionScheme 和一个 IIsCompressionSchemes 元素:
And that's it! This saved us heaps of bandwidth and resulted in a more responsive web application throughout.
就是这样!这为我们节省了大量带宽,并导致整个 Web 应用程序响应速度更快。
Enjoy!
享受!
回答by Sam
Rejuicer is a great new minifier for ASP.NET that's getting a lot of buzz: http://rejuice.me
Rejuicer 是 ASP.NET 的一个很棒的新缩小器,引起了很多关注:http://rejuice.me
It is configured as a HTTP module & performs minification at run-time (once) and caches the output.
它被配置为 HTTP 模块并在运行时(一次)执行缩小并缓存输出。
It:
它:
- Has a fluent interface for configuration
- Allows you to specify files to minify with wildcard rules
- Runs on Windows Azure
- Somewhat magically turns itself off in development environments, so you can debug your original javascript code (not minified).
- 具有流畅的配置界面
- 允许您使用通配符规则指定要缩小的文件
- 在 Windows Azure 上运行
- 在开发环境中有点神奇地关闭自己,因此您可以调试原始 javascript 代码(未缩小)。
The configuration (done on ApplicationStart in global.asax.cs) is as simple as:
配置(在 global.asax.cs 中的 ApplicationStart 上完成)非常简单:
OnRequest.ForJs("~/Combined.js")
.Compact
.FilesIn("~/Scripts/")
.Matching("*.js")
.Cache
.Configure();
回答by ShadowChaser
I use a customized solution based on MSBuild and the Microsoft Ajax Minifier. Much of the existing blog posts out there don't correctly handle certain cases such as integration with TFS build.
我使用基于 MSBuild 和 Microsoft Ajax Minifier 的定制解决方案。许多现有的博客文章都没有正确处理某些情况,例如与 TFS 构建的集成。
For each web project, we create a "wpp.targets" file to extend the Web Publishing Pipeline. For example, if the project is "Website.csproj" create a file named "Website.wpp.targets" in the project.
对于每个 Web 项目,我们创建一个“wpp.targets”文件来扩展 Web 发布管道。例如,如果项目是“Website.csproj”,则在项目中创建一个名为“Website.wpp.targets”的文件。
Place the following code in the targets file:
将以下代码放在目标文件中:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath32)\PATH TO YOUR MSBUILD MINIFY TARGETS" />
<!-- Hook up minification task to WPP build process -->
<PropertyGroup>
<OnAfterPipelineTransformPhase>
$(OnAfterPipelineTransformPhase);
MinifyResourceFiles;
</OnAfterPipelineTransformPhase>
</PropertyGroup>
<!-- Define temporary location to store minified resources -->
<PropertyGroup>
<MinifyResourceIntermediateOutput Condition="'$(MinifyResourceIntermediateOutput)'==''">MinifyResourceFiles</MinifyResourceIntermediateOutput>
<MinifyResourceIntermediateLocation Condition="'$(MinifyResourceIntermediateLocation)'==''">$(_WPPDefaultIntermediateOutputPath)$(MinifyResourceIntermediateOutput)</MinifyResourceIntermediateLocation>
</PropertyGroup>
<Target Name="MinifyResourceFiles" DependsOnTargets="PipelineCollectFilesPhase" Condition="'$(Configuration)' == 'Release'">
<!-- Create lists of the resources to minify -->
<!-- These extract all Javascript and CSS files from the publishing pipeline "FilesForPackagingFromProject" and create two new lists.
The "MinifiedFile" metadata on each item contains the temporary location where the minified file will be stored -->
<ItemGroup>
<JavaScriptToMinify Include="@(FilesForPackagingFromProject)"
Condition="'%(FilesForPackagingFromProject.Extension)' == '.js'">
<MinifiedFile>$(MinifyResourceIntermediateLocation)\minified\%(DestinationRelativePath)</MinifiedFile>
</JavaScriptToMinify>
<StylesheetToMinify Include="@(FilesForPackagingFromProject)"
Condition="'%(FilesForPackagingFromProject.Extension)' == '.css'">
<MinifiedFile>$(MinifyResourceIntermediateLocation)\minified\%(DestinationRelativePath)</MinifiedFile>
</StylesheetToMinify>
</ItemGroup>
<!-- Minify resources -->
<!-- These commands should be replaced with the MSBuild Tasks used to perform your minification
I use my own custom tasks based on the Microsoft Ajax Minifier DLL
The input of the minifier takes a source file directly from the project and outputs to a temporary location -->
<MinifyJavaScript SourceFiles="@(JavaScriptToMinify)" DestinationFiles="@(JavaScriptToMinify->'%(MinifiedFile)')"
Comments="None" />
<MinifyStylesheet SourceFiles="@(StylesheetToMinify)" DestinationFiles="@(StylesheetToMinify->'%(MinifiedFile)')"
Comments="None" />
<!-- Remove the original source files from the packaging system and include the new minfied resources from the temporary location -->
<ItemGroup>
<!--Remove unminified resources from the pipeline -->
<FilesForPackagingFromProject Remove="@(JavaScriptToMinify)" Condition="'@(JavaScriptToMinify)' != ''" />
<FilesForPackagingFromProject Remove="@(StylesheetToMinify)" Condition="'@(StylesheetToMinify)' != ''" />
<!--Add the minified resources at the new loction to the pipeline -->
<FilesForPackagingFromProject Include="@(JavaScriptToMinify->'%(MinifiedFile)')" Condition="'@(JavaScriptToMinify)' != ''"/>
<FilesForPackagingFromProject Include="@(StylesheetToMinify->'%(MinifiedFile)')" Condition="'@(StylesheetToMinify)' != ''"/>
</ItemGroup>
</Target>
</Project>
The "'$(Configuration') == 'Release'" condition on the minification target can be modified depending on your needs. It will automatically minify (and validate) all CSS and JS files in the project when publishing, packaging, and building on the server.
可以根据您的需要修改缩小目标上的“'$(Configuration') == 'Release'”条件。在服务器上发布、打包和构建时,它会自动缩小(并验证)项目中的所有 CSS 和 JS 文件。
You may need to enable the WPP "CopyWebApplication" target for server builds. To do this, set the MSBuild property UseWP_CopyWebApplication to True, and PipelineDependsOnBuild to False. We set these in the project file, before the web application targets file is included.
您可能需要为服务器构建启用 WPP“CopyWebApplication”目标。为此,请将 MSBuild 属性 UseWP_CopyWebApplication 设置为 True,并将 PipelineDependsOnBuild 设置为 False。在包含 Web 应用程序目标文件之前,我们将这些设置在项目文件中。
回答by Matt Wrock
I'd recommend http://www.RequestReduce.comwhich minimizes and combines css and javascript as well as sprites css background images and optimizes their PNG compression. It does all of this at run time and caches the output. It requires no code or configuration beyond adding the HttpModule. It serves all cached content with optimized far future headers and ETags to ensure that browsers cache the css/javascript/sprites as long as possible. While it requires no configuration, it is highly configurable and can be setup to run with a CDN and sync cached files accross a web farm.
我推荐http://www.RequestReduce.com,它最小化并结合了 css 和 javascript 以及精灵 css 背景图像并优化了它们的 PNG 压缩。它在运行时完成所有这些工作并缓存输出。除了添加 HttpModule 之外,它不需要任何代码或配置。它为所有缓存的内容提供优化的远期标题和 ETag,以确保浏览器尽可能长时间地缓存 css/javascript/sprites。虽然它不需要配置,但它是高度可配置的,可以设置为与 CDN 一起运行并同步跨 Web 场的缓存文件。
All javascript, images and css are fetched via HTTP so it can include css and js from third parties and its also a great way to minify/combine .axd resources like WebResource.axd and ScriptResource.axd. It determines the presense of js and css via content-type so the target resource can have any (or no) extension. It runs on any IIS based technology including all versions and view engines of MVC, web forms and "web pages".
所有 javascript、图像和 css 都是通过 HTTP 获取的,因此它可以包含来自第三方的 css 和 js,这也是缩小/组合 .axd 资源(如 WebResource.axd 和 ScriptResource.axd)的好方法。它通过 content-type 确定 js 和 css 的存在,因此目标资源可以有任何(或没有)扩展名。它可以在任何基于 IIS 的技术上运行,包括 MVC、Web 表单和“网页”的所有版本和视图引擎。
You can download from http://www.RequestReduce.com, Nuget or fork from https://github.com/mwrock/RequestReduce.
您可以从http://www.RequestReduce.com下载,Nuget 或从https://github.com/mwrock/RequestReducefork下载。