• ASP.NET MVC Bundles 用法和说明(打包javascript和css)


    在网页中,我们经常需要引用大量的javascript和css文件,在加上许多javascript库都包含debug版和经过压缩的release版(比如jquery),不仅麻烦还很容易引起混乱,所以ASP.NET MVC4引入了Bundles特性,使得我们可以方便的管理javascript和css文件。

    原来,我们引用css和javascript文件我们需要这样一个一个的引用:

    复制代码代码如下:

    <scriptsrc="~/Scripts/jquery-1.8.2.js"></script>
    <scriptsrc="~/Scripts/jquery-ui-1.8.24.js"></script>
    <scriptsrc="~/Scripts/jquery.validate.js"></script>
    <linkhref="~/Content/Site.css"rel="stylesheet"/>

    当需要引用文件的数量较少时还好,但一旦每个页面都需要引用较多文件时,会造成极大的不便,当我们想更换某个引用文件时,将会浪费大量的时间。发布时,还要将一些库替换成release版,比如上面的jquery-1.8.2.js所对应的jquery-1.8.2.min.js

    还好,现在我们可以使用Bundles特性:

    复制代码代码如下:

    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery")
            .Include("~/Scripts/jquery-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryui")
            .Include("~/Scripts/jquery-ui-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryval")
            .Include("~/Scripts/jquery.unobtrusive*"
            ,"~/Scripts/jquery.validate*"));
            bundles.Add(new StyleBundle("~/Content/css")
            .Include("~/Content/site.css"));
        }
    }

    接着在Global.asax文件的Application_Start方法中调用BundleConfig.RegisterBundles方法:

    复制代码代码如下:

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

    在上面我们可以看到我们按照功能的不同,将不同的文件分到了相应的Bundle(Bundle就是包的意思),其中构造函数中的string参数是Bundle的名称,Include函数是将参数相应的文件包含成一个Bundle。可以发现,对于jquery库我们使用了这样的名称~/Scripts/jquery-{version}.js,其中{version}部分代表版本号的意思,MVC将会替我们在Scripts文件中寻找对应的"jquery-版本号.js"文件,并且在非debug模式下,MVC则会使用“jquery-版本号.min.js"文件。

    我们还看到我们使用了这样的名称~/Scripts/jquery.validate*的名称,*是一个通配符,这就意味着Scripts文件夹下的所有前缀为jquery.validate的文件都将包含在同一个Bundle中。

    最后,我们可以View上使用Bundle来代替原来引用的方式:

    复制代码代码如下:

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/jquery")
  • 相关阅读:
    Leetcode: Increasing Triplet Subsequence
    Snapchat面经(师兄的)
    M面经prepare: Shuffle a deck
    M面经Prepare: Find integer Average of 2 integers.
    M面经Prepare: Positive-Negative partitioning preserving order
    M面经Prepare: Delete Words Starting With One Character
    Lintcode: Subtree
    Leetcode: Reconstruct Itinerary
    Groupon面经:Find paths in a binary tree summing to a target value
    一些小感悟(2014.04版)
  • 原文地址:https://www.cnblogs.com/sjqq/p/7307296.html
Copyright © 2020-2023  润新知