在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做Bundle的东西,它用来将js和css进行压缩(多个文件可以打包成一个文件),并且可以区分调试和非调试,在调试时不进行压缩,以原始方式显示出来,以方便查找问题。
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
其中的bundles.Add是在向网站的BundleTable中添加Bundle项,这里主要有ScriptBundle和StyleBundle,分别用来压缩脚本和样式表。用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在,然后在新Bundle的基础上Include项目中的文件进去。
默认情况下,Bundle是会对js和css进行压缩打包的,不过有一个属性可以显式的说明是否需要打包压缩:
BundleTable.EnableOptimizations = true;
在使用时,在相应位置调用ScriptRender和StyleRender的Render方法:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
最终用户页面即可达到效果打包压缩效果。
有一个地方主要注意,在Web.config中,当compilation编译的debug属性设为true时,表示项目处于调试模式,这时Bundle是不会将文件进行打包压缩的,页面中引用的js和css会分散原样的展示在html中,这样做是为了调试时查找问题方便。
<compilation debug="true" targetFramework="4.5.2" />
最终部署运行时,将debug设为false就可以看到js和css被打包和压缩了。