ASP.NET MVC BundleConfig介绍和使用
1、BundleConfig介绍:
在创建ASP.NET MVC5项目时,默认在App_Start文件夹中创建了BudleConfig.cs文件。
public class BundleConfig { // For more information on bundling, visit https://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*")); // 使用要用于开发和学习的 Modernizr 的开发版本。然后,当你做好 // ready for production, use the build tool at https://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")); BundleTable.EnableOptimizations = true; //是否打包压缩 } }
在Global.asax 文件Application_Start()方法中调用了BudleConfig类中RegisterBundles方法。
BundleConfig.RegisterBundles(BundleTable.Bundles);
其中的bundles.Add是在向网站的BundleTable中添加Bundle项,这里主要有ScriptBundle和StyleBundle,分别用来压缩脚本和样式表。用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在,然后在新Bundle的基础上Include项目中的文件进去。具体的Include语法可以查阅上面提供的官方简介。
默认情况下,Bundle是会对js和css进行压缩打包的,不过有一个属性可以显式的说明是否需要打包压缩:
BundleTable.EnableOptimizations = true;
在Web.config中,当compilation的debug属性设为true时,表示项目处于调试模式,这时Bundle是不会将文件进行打包压缩的。
<system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules> </system.web>
2、BundleConfig使用:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js"));
通过ScriptBundle实例添加多个js打包压缩,"~/bundles/bootstrap" 为Bundle名字,Include方法添加多个js文件,中间使用逗号分割。(StyleBundle用来打包压缩css样式文件的,用法一样)
视图中调用方法:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/bootstrap")
补充:“~/Scripts/jquery-{version}.js”,{version}匹配对应文件的任何版本并通过工程配置文件选择正常版本还是缩小版,具体是web.config中的debug设置,如果为true选择正常版本,false则是缩小版。需要注意的是我们不能把相同文件的不同版本号放在一起,比如“jquery-1.7.2.js”和“jquery-1.7.1.js”,两个版本号都会被发送给客户端反而造成混淆。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?