ASP.NET.MVC BundleConfig的使用方法
创建BundleConfig.cs文件,主要用来压缩js和css文件
示例:
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 的开发版本。然后,当你做好
// 生产准备就绪,请使用 https://modernizr.com 上的生成工具仅选择所需的测试。
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap-datetimepicker.min.js",
"~/Scripts/bootstrap-datetimepicker.zh-CN.js",
"~/Scripts/fileinput.js",
"~/Content/bootstrap-fileinput/themes/explorer/theme.min.js",
"~/Scripts/locales/zh.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/xterm.css",
"~/Content/font-awesome.min.css",
"~/Content/bootstrap-datetimepicker.min.css",
"~/Content/bootstrap-fileinput/css/fileinput.css",
"~/Content/bootstrap-fileinput/themes/explorer/theme.css",
"~/Content/site.css"));
BundleTable.EnableOptimizations = true;
}
}
bundles.Add是在向网站的BundleTable中添加Bundle项,这里主要有ScriptBundle和StyleBundle,分别用来压缩脚本和样式表。用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在,然后在新Bundle的基础上Include项目中的文件进去。具体的Include语法可以查阅上面提供的官方简介。
默认情况下,Bundle是会对js和css进行压缩打包的,有一个属性可以显式的说明是否需要打包压缩:
BundleTable.EnableOptimizations = true;
视图中调用方法:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/bootstrap")