ASP.NET MVC使用Bundle来打包压缩js和css

Bundle它是用来将js和css进行压缩(多个文件可以打包成一个文件),并且可以区分调试和非调试,在调试时不进行压缩,以原始方式显示出来,以方便查找问题。

1.BundleConfig配置Bundle

    public class BundleConfig
    {
        // 有关绑定的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            //{version}模糊匹配 加载所有的版本
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));
           
            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"));

            // 将 EnableOptimizations 设为 false 以进行调试。有关详细信息,
            // 请访问 http://go.microsoft.com/fwlink/?LinkId=301862
            BundleTable.EnableOptimizations = true;
        }
    }

2.确保Application_Start是网站程序的开始程序有BundleConfig的注册方法

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

3.配置

BundleConfig的BundleTable.EnableOptimizations = false;和Web.config的<compilation debug="true" targetFramework="4.5" />   表示调试状态文件不压缩
BundleConfig的BundleTable.EnableOptimizations = true;和Web.config的<compilation debug="false" targetFramework="4.5" />   表示发布状态文件压缩
原文地址:https://www.cnblogs.com/lgxlsm/p/5431755.html